]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - glsdk/gst-plugins-ugly0-10.git/blob - ext/x264/gstx264enc.c
x264enc: Set max bitrate in quality mode
[glsdk/gst-plugins-ugly0-10.git] / ext / x264 / gstx264enc.c
1 /* GStreamer H264 encoder plugin
2  * Copyright (C) 2005 Michal Benes <michal.benes@itonis.tv>
3  * Copyright (C) 2005 Josef Zlomek <josef.zlomek@itonis.tv>
4  * Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sf.net>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
22 /**
23  * SECTION:element-x264enc
24  * @see_also: faac
25  *
26  * This element encodes raw video into H264 compressed data,
27  * also otherwise known as MPEG-4 AVC (Advanced Video Codec).
28  *
29  * The #GstX264Enc:pass property controls the type of encoding.  In case of Constant
30  * Bitrate Encoding (actually ABR), the #GstX264Enc:bitrate will determine the quality
31  * of the encoding.  This will similarly be the case if this target bitrate
32  * is to obtained in multiple (2 or 3) pass encoding.
33  * Alternatively, one may choose to perform Constant Quantizer or Quality encoding,
34  * in which case the #GstX264Enc:quantizer property controls much of the outcome, in that case #GstX264Enc:bitrate is the maximum bitrate.
35  *
36  * The H264 profile that is eventually used depends on a few settings.
37  * If #GstX264Enc:dct8x8 is enabled, then High profile is used.
38  * Otherwise, if #GstX264Enc:cabac entropy coding is enabled or #GstX264Enc:bframes
39  * are allowed, then Main Profile is in effect, and otherwise Baseline profile
40  * applies.  No profile is imposed by default, which is fine for most software
41  * players and settings, but in some cases (e.g. hardware platforms) a more
42  * restricted profile/level may be necessary.
43  *
44  * If a preset/tuning are specified then these will define the default values and
45  * the property defaults will be ignored. After this the option-string property is
46  * applied, followed by the user-set properties, fast first pass restrictions and
47  * finally the profile restrictions.
48  *
49  * <note>Some settings, including the default settings, may lead to quite
50  * some latency (i.e. frame buffering) in the encoder. This may cause problems
51  * with pipeline stalling in non-trivial pipelines, because the encoder latency
52  * is often considerably higher than the default size of a simple queue
53  * element. Such problems are caused by one of the queues in the other
54  * non-x264enc streams/branches filling up and blocking upstream. They can
55  * be fixed by relaxing the default time/size/buffer limits on the queue
56  * elements in the non-x264 branches, or using a (single) multiqueue element
57  * for all branches. Also see the last example below.
58  * </note>
59  *
60  * <refsect2>
61  * <title>Example pipeline</title>
62  * |[
63  * gst-launch -v videotestsrc num-buffers=1000 ! x264enc qp-min=18 ! \
64  *   avimux ! filesink location=videotestsrc.avi
65  * ]| This example pipeline will encode a test video source to H264 muxed in an
66  * AVI container, while ensuring a sane minimum quantization factor to avoid
67  * some (excessive) waste.
68  * |[
69  * gst-launch -v videotestsrc num-buffers=1000 ! x264enc pass=quant ! \
70  *   matroskamux ! filesink location=videotestsrc.avi
71  * ]| This example pipeline will encode a test video source to H264 using fixed
72  * quantization, and muxes it in a Matroska container.
73  * |[
74  * gst-launch -v videotestsrc num-buffers=1000 ! x264enc pass=5 quantizer=25 speed-preset=6 profile=1 ! \
75  *   qtmux ! filesink location=videotestsrc.mov
76  * ]| This example pipeline will encode a test video source to H264 using
77  * constant quality at around Q25 using the 'medium' speed/quality preset and
78  * restricting the options used so that the output is H.264 Baseline Profile
79  * compliant and finally multiplexing the output in Quicktime mov format.
80  * |[
81  * gst-launch -v videotestsrc num-buffers=1000 ! tee name=t ! queue ! xvimagesink \
82  *   t. ! queue ! x264enc rc-lookahead=5 ! fakesink
83  * ]| This example pipeline will encode a test video source to H264 while
84  * displaying the input material at the same time.  As mentioned above,
85  * specific settings are needed in this case to avoid pipeline stalling.
86  * Depending on goals and context, other approaches are possible, e.g.
87  * tune=zerolatency might be configured, or queue sizes increased.
88  * </refsect2>
89  */
91 #ifdef HAVE_CONFIG_H
92 #  include "config.h"
93 #endif
95 #include "gstx264enc.h"
97 #if X264_BUILD >= 71
98 #define X264_DELAYED_FRAMES_API
99 #endif
101 #if X264_BUILD >= 76
102 #define X264_ENC_NALS 1
103 #endif
105 #if X264_BUILD >= 69
106 #define X264_MB_RC
107 #endif
109 #if X264_BUILD >= 78
110 /* b-pyramid was available before but was changed from boolean here */
111 #define X264_B_PYRAMID
112 #endif
114 #if X264_BUILD >= 80
115 #define X264_ENH_THREADING
116 #endif
118 #if X264_BUILD >= 82
119 #define X264_INTRA_REFRESH
120 #endif
122 #if X264_BUILD >= 86
123 #define X264_PRESETS
124 #endif
126 #include <string.h>
127 #include <stdlib.h>
129 GST_DEBUG_CATEGORY_STATIC (x264_enc_debug);
130 #define GST_CAT_DEFAULT x264_enc_debug
132 enum
134   ARG_0,
135   ARG_THREADS,
136   ARG_SLICED_THREADS,
137   ARG_SYNC_LOOKAHEAD,
138   ARG_PASS,
139   ARG_QUANTIZER,
140   ARG_STATS_FILE,
141   ARG_MULTIPASS_CACHE_FILE,
142   ARG_BYTE_STREAM,
143   ARG_BITRATE,
144   ARG_INTRA_REFRESH,
145   ARG_VBV_BUF_CAPACITY,
146   ARG_ME,
147   ARG_SUBME,
148   ARG_ANALYSE,
149   ARG_DCT8x8,
150   ARG_REF,
151   ARG_BFRAMES,
152   ARG_B_ADAPT,
153   ARG_B_PYRAMID,
154   ARG_WEIGHTB,
155   ARG_SPS_ID,
156   ARG_AU_NALU,
157   ARG_TRELLIS,
158   ARG_KEYINT_MAX,
159   ARG_CABAC,
160   ARG_QP_MIN,
161   ARG_QP_MAX,
162   ARG_QP_STEP,
163   ARG_IP_FACTOR,
164   ARG_PB_FACTOR,
165   ARG_RC_MB_TREE,
166   ARG_RC_LOOKAHEAD,
167   ARG_NR,
168   ARG_INTERLACED,
169   ARG_OPTION_STRING,
170   ARG_PROFILE,
171   ARG_SPEED_PRESET,
172   ARG_PSY_TUNE,
173   ARG_TUNE,
174 };
176 #define ARG_THREADS_DEFAULT            0        /* 0 means 'auto' which is 1.5x number of CPU cores */
177 #define ARG_PASS_DEFAULT               0
178 #define ARG_QUANTIZER_DEFAULT          21
179 #define ARG_MULTIPASS_CACHE_FILE_DEFAULT "x264.log"
180 #define ARG_STATS_FILE_DEFAULT         ARG_MULTIPASS_CACHE_FILE_DEFAULT
181 #define ARG_BYTE_STREAM_DEFAULT        FALSE
182 #define ARG_BITRATE_DEFAULT            (2 * 1024)
183 #define ARG_VBV_BUF_CAPACITY_DEFAULT   600
184 #define ARG_ME_DEFAULT                 X264_ME_HEX
185 #define ARG_SUBME_DEFAULT              1
186 #define ARG_ANALYSE_DEFAULT            0
187 #define ARG_DCT8x8_DEFAULT             FALSE
188 #define ARG_REF_DEFAULT                1
189 #define ARG_BFRAMES_DEFAULT            0
190 #define ARG_B_ADAPT_DEFAULT            TRUE
191 #define ARG_B_PYRAMID_DEFAULT          FALSE
192 #define ARG_WEIGHTB_DEFAULT            FALSE
193 #define ARG_SPS_ID_DEFAULT             0
194 #define ARG_AU_NALU_DEFAULT            TRUE
195 #define ARG_TRELLIS_DEFAULT            TRUE
196 #define ARG_KEYINT_MAX_DEFAULT         0
197 #define ARG_CABAC_DEFAULT              TRUE
198 #define ARG_QP_MIN_DEFAULT             10
199 #define ARG_QP_MAX_DEFAULT             51
200 #define ARG_QP_STEP_DEFAULT            4
201 #define ARG_IP_FACTOR_DEFAULT          1.4
202 #define ARG_PB_FACTOR_DEFAULT          1.3
203 #define ARG_NR_DEFAULT                 0
204 #define ARG_INTERLACED_DEFAULT         FALSE
205 #define ARG_SLICED_THREADS_DEFAULT     FALSE
206 #define ARG_SYNC_LOOKAHEAD_DEFAULT     -1
207 #define ARG_RC_MB_TREE_DEFAULT         TRUE
208 #define ARG_RC_LOOKAHEAD_DEFAULT       40
209 #define ARG_INTRA_REFRESH_DEFAULT      FALSE
210 #define ARG_PROFILE_DEFAULT            2        /* 'Main Profile' - matches profile of property defaults */
211 #define ARG_OPTION_STRING_DEFAULT      ""
212 static GString *x264enc_defaults;
213 #define ARG_SPEED_PRESET_DEFAULT       6        /* 'medium' preset - matches x264 CLI default */
214 #define ARG_PSY_TUNE_DEFAULT           0        /* no psy tuning */
215 #define ARG_TUNE_DEFAULT               0        /* no tuning */
217 enum
219   GST_X264_ENC_PASS_CBR = 0,
220   GST_X264_ENC_PASS_QUANT = 0x04,
221   GST_X264_ENC_PASS_QUAL,
222   GST_X264_ENC_PASS_PASS1 = 0x11,
223   GST_X264_ENC_PASS_PASS2,
224   GST_X264_ENC_PASS_PASS3
225 };
227 #define GST_X264_ENC_PASS_TYPE (gst_x264_enc_pass_get_type())
228 static GType
229 gst_x264_enc_pass_get_type (void)
231   static GType pass_type = 0;
233   static const GEnumValue pass_types[] = {
234     {GST_X264_ENC_PASS_CBR, "Constant Bitrate Encoding", "cbr"},
235     {GST_X264_ENC_PASS_QUANT, "Constant Quantizer (debugging only)", "quant"},
236     {GST_X264_ENC_PASS_QUAL, "Constant Quality", "qual"},
237     {GST_X264_ENC_PASS_PASS1, "VBR Encoding - Pass 1", "pass1"},
238     {GST_X264_ENC_PASS_PASS2, "VBR Encoding - Pass 2", "pass2"},
239     {GST_X264_ENC_PASS_PASS3, "VBR Encoding - Pass 3", "pass3"},
240     {0, NULL, NULL}
241   };
243   if (!pass_type) {
244     pass_type = g_enum_register_static ("GstX264EncPass", pass_types);
245   }
246   return pass_type;
249 #define GST_X264_ENC_ME_TYPE (gst_x264_enc_me_get_type())
250 static GType
251 gst_x264_enc_me_get_type (void)
253   static GType me_type = 0;
254   static GEnumValue *me_types;
255   int n, i;
257   if (me_type != 0)
258     return me_type;
260   n = 0;
261   while (x264_motion_est_names[n] != NULL)
262     n++;
264   me_types = g_new0 (GEnumValue, n + 1);
266   for (i = 0; i < n; i++) {
267     me_types[i].value = i;
268     me_types[i].value_name = x264_motion_est_names[i];
269     me_types[i].value_nick = x264_motion_est_names[i];
270   }
272   me_type = g_enum_register_static ("GstX264EncMe", me_types);
274   return me_type;
277 #define GST_X264_ENC_ANALYSE_TYPE (gst_x264_enc_analyse_get_type())
278 static GType
279 gst_x264_enc_analyse_get_type (void)
281   static GType analyse_type = 0;
282   static const GFlagsValue analyse_types[] = {
283     {X264_ANALYSE_I4x4, "i4x4", "i4x4"},
284     {X264_ANALYSE_I8x8, "i8x8", "i8x8"},
285     {X264_ANALYSE_PSUB16x16, "p8x8", "p8x8"},
286     {X264_ANALYSE_PSUB8x8, "p4x4", "p4x4"},
287     {X264_ANALYSE_BSUB16x16, "b8x8", "b8x8"},
288     {0, NULL, NULL},
289   };
291   if (!analyse_type) {
292     analyse_type = g_flags_register_static ("GstX264EncAnalyse", analyse_types);
293   }
294   return analyse_type;
297 #ifdef X264_PRESETS
299 #define GST_X264_ENC_PROFILE_TYPE (gst_x264_enc_profile_get_type())
300 static GType
301 gst_x264_enc_profile_get_type (void)
303   static GType profile_type = 0;
304   static GEnumValue *profile_types;
305   int n, i;
307   if (profile_type != 0)
308     return profile_type;
310   n = 0;
311   while (x264_profile_names[n] != NULL)
312     n++;
314   profile_types = g_new0 (GEnumValue, n + 2);
316   i = 0;
317   profile_types[i].value = i;
318   profile_types[i].value_name = "No profile";
319   profile_types[i].value_nick = "None";
320   for (i = 1; i <= n; i++) {
321     profile_types[i].value = i;
322     profile_types[i].value_name = x264_profile_names[i - 1];
323     profile_types[i].value_nick = x264_profile_names[i - 1];
324   }
326   profile_type = g_enum_register_static ("GstX264EncProfile", profile_types);
328   return profile_type;
331 #define GST_X264_ENC_SPEED_PRESET_TYPE (gst_x264_enc_speed_preset_get_type())
332 static GType
333 gst_x264_enc_speed_preset_get_type (void)
335   static GType speed_preset_type = 0;
336   static GEnumValue *speed_preset_types;
337   int n, i;
339   if (speed_preset_type != 0)
340     return speed_preset_type;
342   n = 0;
343   while (x264_preset_names[n] != NULL)
344     n++;
346   speed_preset_types = g_new0 (GEnumValue, n + 2);
348   speed_preset_types[0].value = 0;
349   speed_preset_types[0].value_name = "No preset";
350   speed_preset_types[0].value_nick = "None";
352   for (i = 1; i <= n; i++) {
353     speed_preset_types[i].value = i;
354     speed_preset_types[i].value_name = x264_preset_names[i - 1];
355     speed_preset_types[i].value_nick = x264_preset_names[i - 1];
356   }
358   speed_preset_type =
359       g_enum_register_static ("GstX264EncPreset", speed_preset_types);
361   return speed_preset_type;
364 static const GFlagsValue tune_types[] = {
365   {0x0, "No tuning", "none"},
366   {0x1, "Still image", "stillimage"},
367   {0x2, "Fast decode", "fastdecode"},
368   {0x4, "Zero latency (requires constant framerate)", "zerolatency"},
369   {0, NULL, NULL},
370 };
372 #define GST_X264_ENC_TUNE_TYPE (gst_x264_enc_tune_get_type())
373 static GType
374 gst_x264_enc_tune_get_type (void)
376   static GType tune_type = 0;
378   if (!tune_type) {
379     tune_type = g_flags_register_static ("GstX264EncTune", tune_types + 1);
380   }
381   return tune_type;
384 enum
386   GST_X264_ENC_TUNE_NONE,
387   GST_X264_ENC_TUNE_FILM,
388   GST_X264_ENC_TUNE_ANIMATION,
389   GST_X264_ENC_TUNE_GRAIN,
390   GST_X264_ENC_TUNE_PSNR,
391   GST_X264_ENC_TUNE_SSIM,
392   GST_X264_ENC_TUNE_LAST
393 };
395 static const GEnumValue psy_tune_types[] = {
396   {GST_X264_ENC_TUNE_NONE, "No tuning", "none"},
397   {GST_X264_ENC_TUNE_FILM, "Film", "film"},
398   {GST_X264_ENC_TUNE_ANIMATION, "Animation", "animation"},
399   {GST_X264_ENC_TUNE_GRAIN, "Grain", "grain"},
400   {GST_X264_ENC_TUNE_PSNR, "PSNR", "psnr"},
401   {GST_X264_ENC_TUNE_SSIM, "SSIM", "ssim"},
402   {0, NULL, NULL},
403 };
405 #define GST_X264_ENC_PSY_TUNE_TYPE (gst_x264_enc_psy_tune_get_type())
406 static GType
407 gst_x264_enc_psy_tune_get_type (void)
409   static GType psy_tune_type = 0;
411   if (!psy_tune_type) {
412     psy_tune_type =
413         g_enum_register_static ("GstX264EncPsyTune", psy_tune_types);
414   }
415   return psy_tune_type;
418 static void
419 gst_x264_enc_build_tunings_string (GstX264Enc * x264enc)
421   int i = 1;
423   if (x264enc->tunings && x264enc->tunings->len)
424     g_string_free (x264enc->tunings, TRUE);
426   if (x264enc->psy_tune) {
427     x264enc->tunings =
428         g_string_new (psy_tune_types[x264enc->psy_tune].value_nick);
429   } else {
430     x264enc->tunings = g_string_new (NULL);
431   }
433   while (tune_types[i].value_name) {
434     if (x264enc->tune & (1 << (i - 1)))
435       g_string_append_printf (x264enc->tunings, "%s%s",
436           x264enc->tunings->len ? "," : "", tune_types[i].value_nick);
437     i++;
438   }
440   if (x264enc->tunings->len)
441     GST_DEBUG_OBJECT (x264enc, "Constructed tunings string: %s",
442         x264enc->tunings->str);
445 #endif
448 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
449     GST_PAD_SINK,
450     GST_PAD_ALWAYS,
451     GST_STATIC_CAPS ("video/x-raw-yuv, "
452         "format = (fourcc) { I420, YV12 }, "
453         "framerate = (fraction) [0, MAX], "
454         "width = (int) [ 16, MAX ], " "height = (int) [ 16, MAX ]")
455     );
457 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
458     GST_PAD_SRC,
459     GST_PAD_ALWAYS,
460     GST_STATIC_CAPS ("video/x-h264, "
461         "framerate = (fraction) [0/1, MAX], "
462         "width = (int) [ 1, MAX ], " "height = (int) [ 1, MAX ], "
463         "stream-format = (string) { byte-stream, avc }, "
464         "alignment = (string) { au }")
465     );
467 static void gst_x264_enc_finalize (GObject * object);
468 static void gst_x264_enc_reset (GstX264Enc * encoder);
470 static gboolean gst_x264_enc_init_encoder (GstX264Enc * encoder);
471 static void gst_x264_enc_close_encoder (GstX264Enc * encoder);
473 static gboolean gst_x264_enc_sink_set_caps (GstPad * pad, GstCaps * caps);
474 static gboolean gst_x264_enc_sink_event (GstPad * pad, GstEvent * event);
475 static gboolean gst_x264_enc_src_event (GstPad * pad, GstEvent * event);
476 static GstFlowReturn gst_x264_enc_chain (GstPad * pad, GstBuffer * buf);
477 static void gst_x264_enc_flush_frames (GstX264Enc * encoder, gboolean send);
478 static GstFlowReturn gst_x264_enc_encode_frame (GstX264Enc * encoder,
479     x264_picture_t * pic_in, int *i_nal, gboolean send);
480 static GstStateChangeReturn gst_x264_enc_change_state (GstElement * element,
481     GstStateChange transition);
483 static void gst_x264_enc_set_property (GObject * object, guint prop_id,
484     const GValue * value, GParamSpec * pspec);
485 static void gst_x264_enc_get_property (GObject * object, guint prop_id,
486     GValue * value, GParamSpec * pspec);
488 static void
489 _do_init (GType object_type)
491   const GInterfaceInfo preset_interface_info = {
492     NULL,                       /* interface_init */
493     NULL,                       /* interface_finalize */
494     NULL                        /* interface_data */
495   };
497   g_type_add_interface_static (object_type, GST_TYPE_PRESET,
498       &preset_interface_info);
501 GST_BOILERPLATE_FULL (GstX264Enc, gst_x264_enc, GstElement, GST_TYPE_ELEMENT,
502     _do_init);
504 static void
505 gst_x264_enc_base_init (gpointer g_class)
507   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
509   gst_element_class_set_details_simple (element_class,
510       "x264enc", "Codec/Encoder/Video", "H264 Encoder",
511       "Josef Zlomek <josef.zlomek@itonis.tv>, "
512       "Mark Nauwelaerts <mnauw@users.sf.net>");
514   gst_element_class_add_pad_template (element_class,
515       gst_static_pad_template_get (&src_factory));
516   gst_element_class_add_pad_template (element_class,
517       gst_static_pad_template_get (&sink_factory));
520 /* don't forget to free the string after use */
521 static const gchar *
522 gst_x264_enc_build_partitions (gint analyse)
524   GString *string;
526   if (!analyse)
527     return NULL;
529   string = g_string_new (NULL);
530   if (analyse & X264_ANALYSE_I4x4)
531     g_string_append (string, "i4x4");
532   if (analyse & X264_ANALYSE_I8x8)
533     g_string_append (string, ",i8x8");
534   if (analyse & X264_ANALYSE_PSUB16x16)
535     g_string_append (string, ",p8x8");
536   if (analyse & X264_ANALYSE_PSUB8x8)
537     g_string_append (string, ",p4x4");
538   if (analyse & X264_ANALYSE_BSUB16x16)
539     g_string_append (string, ",b8x8");
541   return (const gchar *) g_string_free (string, FALSE);
544 static void
545 gst_x264_enc_class_init (GstX264EncClass * klass)
547   GObjectClass *gobject_class;
548   GstElementClass *gstelement_class;
550   const gchar *partitions = NULL;
552   x264enc_defaults = g_string_new ("");
554   gobject_class = (GObjectClass *) klass;
555   gstelement_class = (GstElementClass *) klass;
557   gobject_class->set_property = gst_x264_enc_set_property;
558   gobject_class->get_property = gst_x264_enc_get_property;
559   gobject_class->finalize = gst_x264_enc_finalize;
561   gstelement_class->change_state =
562       GST_DEBUG_FUNCPTR (gst_x264_enc_change_state);
564   /* options for which we don't use string equivalents */
565   g_object_class_install_property (gobject_class, ARG_PASS,
566       g_param_spec_enum ("pass", "Encoding pass/type",
567           "Encoding pass/type", GST_X264_ENC_PASS_TYPE,
568           ARG_PASS_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
569   g_object_class_install_property (gobject_class, ARG_QUANTIZER,
570       g_param_spec_uint ("quantizer", "Constant Quantizer",
571           "Constant quantizer or quality to apply",
572           1, 50, ARG_QUANTIZER_DEFAULT,
573           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
574   g_object_class_install_property (gobject_class, ARG_BITRATE,
575       g_param_spec_uint ("bitrate", "Bitrate", "Bitrate in kbit/sec", 1,
576           100 * 1024, ARG_BITRATE_DEFAULT,
577           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
578   g_object_class_install_property (gobject_class, ARG_VBV_BUF_CAPACITY,
579       g_param_spec_uint ("vbv-buf-capacity", "VBV buffer capacity",
580           "Size of the VBV buffer in milliseconds",
581           0, 10000, ARG_VBV_BUF_CAPACITY_DEFAULT,
582           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
584 #ifdef X264_PRESETS
585   g_object_class_install_property (gobject_class, ARG_SPEED_PRESET,
586       g_param_spec_enum ("speed-preset", "Speed/quality preset",
587           "Preset name for speed/quality tradeoff options (can affect decode "
588           "compatibility - impose restrictions separately for your target decoder)",
589           GST_X264_ENC_SPEED_PRESET_TYPE, ARG_SPEED_PRESET_DEFAULT,
590           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
591   g_object_class_install_property (gobject_class, ARG_PSY_TUNE,
592       g_param_spec_enum ("psy-tune", "Psychovisual tuning preset",
593           "Preset name for psychovisual tuning options",
594           GST_X264_ENC_PSY_TUNE_TYPE, ARG_PSY_TUNE_DEFAULT,
595           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
596   g_object_class_install_property (gobject_class, ARG_TUNE,
597       g_param_spec_flags ("tune", "Content tuning preset",
598           "Preset name for non-psychovisual tuning options",
599           GST_X264_ENC_TUNE_TYPE, ARG_TUNE_DEFAULT,
600           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
601   g_object_class_install_property (gobject_class, ARG_PROFILE,
602       g_param_spec_enum ("profile", "H.264 profile",
603           "Apply restrictions to meet H.264 Profile constraints. This will "
604           "override other properties if necessary.",
605           GST_X264_ENC_PROFILE_TYPE, ARG_PROFILE_DEFAULT,
606           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
607 #endif /* X264_PRESETS */
608   g_object_class_install_property (gobject_class, ARG_OPTION_STRING,
609       g_param_spec_string ("option-string", "Option string",
610           "String of x264 options (overridden by element properties)",
611           ARG_OPTION_STRING_DEFAULT,
612           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
614   /* options for which we _do_ use string equivalents */
615   g_object_class_install_property (gobject_class, ARG_THREADS,
616       g_param_spec_uint ("threads", "Threads",
617           "Number of threads used by the codec (0 for automatic)",
618           0, 4, ARG_THREADS_DEFAULT,
619           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
620   /* NOTE: this first string append doesn't require the ':' delimiter but the
621    * rest do */
622   g_string_append_printf (x264enc_defaults, "threads=%d", ARG_THREADS_DEFAULT);
623 #ifdef X264_ENH_THREADING
624   g_object_class_install_property (gobject_class, ARG_SLICED_THREADS,
625       g_param_spec_boolean ("sliced-threads", "Sliced Threads",
626           "Low latency but lower efficiency threading",
627           ARG_SLICED_THREADS_DEFAULT,
628           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
629   g_string_append_printf (x264enc_defaults, ":sliced-threads=%d",
630       ARG_SLICED_THREADS_DEFAULT);
631   g_object_class_install_property (gobject_class, ARG_SYNC_LOOKAHEAD,
632       g_param_spec_int ("sync-lookahead", "Sync Lookahead",
633           "Number of buffer frames for threaded lookahead (-1 for automatic)",
634           -1, 250, ARG_SYNC_LOOKAHEAD_DEFAULT,
635           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
636   g_string_append_printf (x264enc_defaults, ":sync-lookahead=%d",
637       ARG_SYNC_LOOKAHEAD_DEFAULT);
638 #endif
639   g_object_class_install_property (gobject_class, ARG_STATS_FILE,
640       g_param_spec_string ("stats-file", "Stats File",
641           "Filename for multipass statistics (deprecated, use multipass-cache-file)",
642           ARG_STATS_FILE_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
643   g_object_class_install_property (gobject_class, ARG_MULTIPASS_CACHE_FILE,
644       g_param_spec_string ("multipass-cache-file", "Multipass Cache File",
645           "Filename for multipass cache file",
646           ARG_MULTIPASS_CACHE_FILE_DEFAULT,
647           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
648   g_string_append_printf (x264enc_defaults, ":stats=%s",
649       ARG_MULTIPASS_CACHE_FILE_DEFAULT);
650   g_object_class_install_property (gobject_class, ARG_BYTE_STREAM,
651       g_param_spec_boolean ("byte-stream", "Byte Stream",
652           "Generate byte stream format of NALU", ARG_BYTE_STREAM_DEFAULT,
653           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
654   g_string_append_printf (x264enc_defaults, ":annexb=%d",
655       ARG_BYTE_STREAM_DEFAULT);
656 #ifdef X264_INTRA_REFRESH
657   g_object_class_install_property (gobject_class, ARG_INTRA_REFRESH,
658       g_param_spec_boolean ("intra-refresh", "Intra Refresh",
659           "Use Periodic Intra Refresh instead of IDR frames",
660           ARG_INTRA_REFRESH_DEFAULT,
661           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
662   g_string_append_printf (x264enc_defaults, ":intra-refresh=%d",
663       ARG_INTRA_REFRESH_DEFAULT);
664 #endif
665   g_object_class_install_property (gobject_class, ARG_ME,
666       g_param_spec_enum ("me", "Motion Estimation",
667           "Integer pixel motion estimation method", GST_X264_ENC_ME_TYPE,
668           ARG_ME_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
669   g_string_append_printf (x264enc_defaults, ":me=%s",
670       x264_motion_est_names[ARG_ME_DEFAULT]);
671   g_object_class_install_property (gobject_class, ARG_SUBME,
672       g_param_spec_uint ("subme", "Subpixel Motion Estimation",
673           "Subpixel motion estimation and partition decision quality: 1=fast, 6=best",
674           1, 6, ARG_SUBME_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
675   g_string_append_printf (x264enc_defaults, ":subme=%d", ARG_SUBME_DEFAULT);
676   g_object_class_install_property (gobject_class, ARG_ANALYSE,
677       g_param_spec_flags ("analyse", "Analyse", "Partitions to consider",
678           GST_X264_ENC_ANALYSE_TYPE, ARG_ANALYSE_DEFAULT,
679           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
680   partitions = gst_x264_enc_build_partitions (ARG_ANALYSE_DEFAULT);
681   if (partitions) {
682     g_string_append_printf (x264enc_defaults, ":partitions=%s", partitions);
683     g_free ((gpointer) partitions);
684   }
685   g_object_class_install_property (gobject_class, ARG_DCT8x8,
686       g_param_spec_boolean ("dct8x8", "DCT8x8",
687           "Adaptive spatial transform size", ARG_DCT8x8_DEFAULT,
688           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
689   g_string_append_printf (x264enc_defaults, ":8x8dct=%d", ARG_DCT8x8_DEFAULT);
690   g_object_class_install_property (gobject_class, ARG_REF,
691       g_param_spec_uint ("ref", "Reference Frames",
692           "Number of reference frames",
693           1, 12, ARG_REF_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
694   g_string_append_printf (x264enc_defaults, ":ref=%d", ARG_REF_DEFAULT);
695   g_object_class_install_property (gobject_class, ARG_BFRAMES,
696       g_param_spec_uint ("bframes", "B-Frames",
697           "Number of B-frames between I and P",
698           0, 4, ARG_BFRAMES_DEFAULT,
699           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
700   g_string_append_printf (x264enc_defaults, ":bframes=%d", ARG_BFRAMES_DEFAULT);
701   g_object_class_install_property (gobject_class, ARG_B_ADAPT,
702       g_param_spec_boolean ("b-adapt", "B-Adapt",
703           "Automatically decide how many B-frames to use",
704           ARG_B_ADAPT_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
705   g_string_append_printf (x264enc_defaults, ":b-adapt=%d", ARG_B_ADAPT_DEFAULT);
706   g_object_class_install_property (gobject_class, ARG_B_PYRAMID,
707       g_param_spec_boolean ("b-pyramid", "B-Pyramid",
708           "Keep some B-frames as references", ARG_B_PYRAMID_DEFAULT,
709           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
710 #ifdef X264_B_PYRAMID
711   g_string_append_printf (x264enc_defaults, ":b-pyramid=%s",
712       x264_b_pyramid_names[ARG_B_PYRAMID_DEFAULT]);
713 #else
714   g_string_append_printf (x264enc_defaults, ":b-pyramid=%d",
715       ARG_B_PYRAMID_DEFAULT);
716 #endif /* X264_B_PYRAMID */
717   g_object_class_install_property (gobject_class, ARG_WEIGHTB,
718       g_param_spec_boolean ("weightb", "Weighted B-Frames",
719           "Weighted prediction for B-frames", ARG_WEIGHTB_DEFAULT,
720           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
721   g_string_append_printf (x264enc_defaults, ":weightb=%d", ARG_WEIGHTB_DEFAULT);
722   g_object_class_install_property (gobject_class, ARG_SPS_ID,
723       g_param_spec_uint ("sps-id", "SPS ID",
724           "SPS and PPS ID number",
725           0, 31, ARG_SPS_ID_DEFAULT,
726           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
727   g_string_append_printf (x264enc_defaults, ":sps-id=%d", ARG_SPS_ID_DEFAULT);
728   g_object_class_install_property (gobject_class, ARG_AU_NALU,
729       g_param_spec_boolean ("aud", "AUD",
730           "Use AU (Access Unit) delimiter", ARG_AU_NALU_DEFAULT,
731           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
732   g_string_append_printf (x264enc_defaults, ":aud=%d", ARG_AU_NALU_DEFAULT);
733   g_object_class_install_property (gobject_class, ARG_TRELLIS,
734       g_param_spec_boolean ("trellis", "Trellis quantization",
735           "Enable trellis searched quantization", ARG_TRELLIS_DEFAULT,
736           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
737   g_string_append_printf (x264enc_defaults, ":trellis=%d", ARG_TRELLIS_DEFAULT);
738   g_object_class_install_property (gobject_class, ARG_KEYINT_MAX,
739       g_param_spec_uint ("key-int-max", "Key-frame maximal interval",
740           "Maximal distance between two key-frames (0 for automatic)",
741           0, G_MAXINT, ARG_KEYINT_MAX_DEFAULT,
742           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
743   g_string_append_printf (x264enc_defaults, ":keyint=%d",
744       ARG_KEYINT_MAX_DEFAULT);
745   g_object_class_install_property (gobject_class, ARG_CABAC,
746       g_param_spec_boolean ("cabac", "Use CABAC", "Enable CABAC entropy coding",
747           ARG_CABAC_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
748   g_string_append_printf (x264enc_defaults, ":cabac=%d", ARG_CABAC_DEFAULT);
749   g_object_class_install_property (gobject_class, ARG_QP_MIN,
750       g_param_spec_uint ("qp-min", "Minimum Quantizer",
751           "Minimum quantizer", 1, 51, ARG_QP_MIN_DEFAULT,
752           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
753   g_string_append_printf (x264enc_defaults, ":qpmin=%d", ARG_QP_MIN_DEFAULT);
754   g_object_class_install_property (gobject_class, ARG_QP_MAX,
755       g_param_spec_uint ("qp-max", "Maximum Quantizer",
756           "Maximum quantizer", 1, 51, ARG_QP_MAX_DEFAULT,
757           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
758   g_string_append_printf (x264enc_defaults, ":qpmax=%d", ARG_QP_MAX_DEFAULT);
759   g_object_class_install_property (gobject_class, ARG_QP_STEP,
760       g_param_spec_uint ("qp-step", "Maximum Quantizer Difference",
761           "Maximum quantizer difference between frames",
762           1, 50, ARG_QP_STEP_DEFAULT,
763           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
764   g_string_append_printf (x264enc_defaults, ":qpstep=%d", ARG_QP_STEP_DEFAULT);
765   g_object_class_install_property (gobject_class, ARG_IP_FACTOR,
766       g_param_spec_float ("ip-factor", "IP-Factor",
767           "Quantizer factor between I- and P-frames",
768           0, 2, ARG_IP_FACTOR_DEFAULT,
769           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
770   g_string_append_printf (x264enc_defaults, ":ip-factor=%f",
771       ARG_IP_FACTOR_DEFAULT);
772   g_object_class_install_property (gobject_class, ARG_PB_FACTOR,
773       g_param_spec_float ("pb-factor", "PB-Factor",
774           "Quantizer factor between P- and B-frames", 0, 2,
775           ARG_PB_FACTOR_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
776   g_string_append_printf (x264enc_defaults, ":pb-factor=%f",
777       ARG_PB_FACTOR_DEFAULT);
778 #ifdef X264_MB_RC
779   g_object_class_install_property (gobject_class, ARG_RC_MB_TREE,
780       g_param_spec_boolean ("mb-tree", "Macroblock Tree",
781           "Macroblock-Tree ratecontrol",
782           ARG_RC_MB_TREE_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
783   g_string_append_printf (x264enc_defaults, ":mbtree=%d",
784       ARG_RC_MB_TREE_DEFAULT);
785   g_object_class_install_property (gobject_class, ARG_RC_LOOKAHEAD,
786       g_param_spec_int ("rc-lookahead", "Rate Control Lookahead",
787           "Number of frames for frametype lookahead", 0, 250,
788           ARG_RC_LOOKAHEAD_DEFAULT,
789           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
790   g_string_append_printf (x264enc_defaults, ":rc-lookahead=%d",
791       ARG_RC_LOOKAHEAD_DEFAULT);
792 #endif
793   g_object_class_install_property (gobject_class, ARG_NR,
794       g_param_spec_uint ("noise-reduction", "Noise Reduction",
795           "Noise reduction strength",
796           0, 100000, ARG_NR_DEFAULT,
797           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
798   g_string_append_printf (x264enc_defaults, ":nr=%d", ARG_NR_DEFAULT);
799   g_object_class_install_property (gobject_class, ARG_INTERLACED,
800       g_param_spec_boolean ("interlaced", "Interlaced",
801           "Interlaced material", ARG_INTERLACED_DEFAULT,
802           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
803   g_string_append_printf (x264enc_defaults, ":interlaced=%d",
804       ARG_INTERLACED_DEFAULT);
806   /* append deblock parameters */
807   g_string_append_printf (x264enc_defaults, ":deblock=0,0");
808   /* append weighted prediction parameter */
809   g_string_append_printf (x264enc_defaults, ":weightp=0");
812 static void
813 gst_x264_enc_log_callback (gpointer private, gint level, const char *format,
814     va_list args)
816 #ifndef GST_DISABLE_GST_DEBUG
817   GstDebugLevel gst_level;
818   GObject *object = (GObject *) private;
820   switch (level) {
821     case X264_LOG_NONE:
822       gst_level = GST_LEVEL_NONE;
823       break;
824     case X264_LOG_ERROR:
825       gst_level = GST_LEVEL_ERROR;
826       break;
827     case X264_LOG_WARNING:
828       gst_level = GST_LEVEL_WARNING;
829       break;
830     case X264_LOG_INFO:
831       gst_level = GST_LEVEL_INFO;
832       break;
833     default:
834       /* push x264enc debug down to our lower levels to avoid some clutter */
835       gst_level = GST_LEVEL_LOG;
836       break;
837   }
839   gst_debug_log_valist (x264_enc_debug, gst_level, "", "", 0, object, format,
840       args);
841 #endif /* GST_DISABLE_GST_DEBUG */
844 /* initialize the new element
845  * instantiate pads and add them to element
846  * set functions
847  * initialize structure
848  */
849 static void
850 gst_x264_enc_init (GstX264Enc * encoder, GstX264EncClass * klass)
852   encoder->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
853   gst_pad_set_setcaps_function (encoder->sinkpad,
854       GST_DEBUG_FUNCPTR (gst_x264_enc_sink_set_caps));
855   gst_pad_set_event_function (encoder->sinkpad,
856       GST_DEBUG_FUNCPTR (gst_x264_enc_sink_event));
857   gst_pad_set_chain_function (encoder->sinkpad,
858       GST_DEBUG_FUNCPTR (gst_x264_enc_chain));
859   gst_element_add_pad (GST_ELEMENT (encoder), encoder->sinkpad);
861   encoder->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
862   gst_pad_use_fixed_caps (encoder->srcpad);
863   gst_element_add_pad (GST_ELEMENT (encoder), encoder->srcpad);
865   gst_pad_set_event_function (encoder->srcpad,
866       GST_DEBUG_FUNCPTR (gst_x264_enc_src_event));
868   /* properties */
869   encoder->threads = ARG_THREADS_DEFAULT;
870   encoder->sliced_threads = ARG_SLICED_THREADS_DEFAULT;
871   encoder->sync_lookahead = ARG_SYNC_LOOKAHEAD_DEFAULT;
872   encoder->pass = ARG_PASS_DEFAULT;
873   encoder->quantizer = ARG_QUANTIZER_DEFAULT;
874   encoder->mp_cache_file = g_strdup (ARG_MULTIPASS_CACHE_FILE_DEFAULT);
875   encoder->byte_stream = ARG_BYTE_STREAM_DEFAULT;
876   encoder->bitrate = ARG_BITRATE_DEFAULT;
877   encoder->intra_refresh = ARG_INTRA_REFRESH_DEFAULT;
878   encoder->vbv_buf_capacity = ARG_VBV_BUF_CAPACITY_DEFAULT;
879   encoder->me = ARG_ME_DEFAULT;
880   encoder->subme = ARG_SUBME_DEFAULT;
881   encoder->analyse = ARG_ANALYSE_DEFAULT;
882   encoder->dct8x8 = ARG_DCT8x8_DEFAULT;
883   encoder->ref = ARG_REF_DEFAULT;
884   encoder->bframes = ARG_BFRAMES_DEFAULT;
885   encoder->b_adapt = ARG_B_ADAPT_DEFAULT;
886   encoder->b_pyramid = ARG_B_PYRAMID_DEFAULT;
887   encoder->weightb = ARG_WEIGHTB_DEFAULT;
888   encoder->sps_id = ARG_SPS_ID_DEFAULT;
889   encoder->au_nalu = ARG_AU_NALU_DEFAULT;
890   encoder->trellis = ARG_TRELLIS_DEFAULT;
891   encoder->keyint_max = ARG_KEYINT_MAX_DEFAULT;
892   encoder->cabac = ARG_CABAC_DEFAULT;
893   encoder->qp_min = ARG_QP_MIN_DEFAULT;
894   encoder->qp_max = ARG_QP_MAX_DEFAULT;
895   encoder->qp_step = ARG_QP_STEP_DEFAULT;
896   encoder->ip_factor = ARG_IP_FACTOR_DEFAULT;
897   encoder->pb_factor = ARG_PB_FACTOR_DEFAULT;
898   encoder->mb_tree = ARG_RC_MB_TREE_DEFAULT;
899   encoder->rc_lookahead = ARG_RC_LOOKAHEAD_DEFAULT;
900   encoder->noise_reduction = ARG_NR_DEFAULT;
901   encoder->interlaced = ARG_INTERLACED_DEFAULT;
902   encoder->profile = ARG_PROFILE_DEFAULT;
903   encoder->option_string = g_string_new (NULL);
904   encoder->option_string_prop = g_string_new (ARG_OPTION_STRING_DEFAULT);
905   encoder->speed_preset = ARG_SPEED_PRESET_DEFAULT;
906   encoder->psy_tune = ARG_PSY_TUNE_DEFAULT;
907   encoder->tune = ARG_TUNE_DEFAULT;
909   /* resources */
910   encoder->delay = g_queue_new ();
911   encoder->buffer_size = 100000;
912   encoder->buffer = g_malloc (encoder->buffer_size);
914   x264_param_default (&encoder->x264param);
916   /* log callback setup; part of parameters */
917   encoder->x264param.pf_log = gst_x264_enc_log_callback;
918   encoder->x264param.p_log_private = encoder;
919   encoder->x264param.i_log_level = X264_LOG_DEBUG;
921   gst_x264_enc_reset (encoder);
924 static void
925 gst_x264_enc_reset (GstX264Enc * encoder)
927   encoder->x264enc = NULL;
928   encoder->width = 0;
929   encoder->height = 0;
931   GST_OBJECT_LOCK (encoder);
932   encoder->i_type = X264_TYPE_AUTO;
933   if (encoder->forcekeyunit_event)
934     gst_event_unref (encoder->forcekeyunit_event);
935   encoder->forcekeyunit_event = NULL;
936   GST_OBJECT_UNLOCK (encoder);
939 static void
940 gst_x264_enc_finalize (GObject * object)
942   GstX264Enc *encoder = GST_X264_ENC (object);
944 #define FREE_STRING(ptr) \
945   if (ptr) \
946     ptr = (GString *)g_string_free (ptr, TRUE);
948   FREE_STRING (encoder->tunings);
949   FREE_STRING (encoder->option_string);
950   FREE_STRING (encoder->option_string_prop);
952 #undef FREE_STRING
954   g_free (encoder->mp_cache_file);
955   encoder->mp_cache_file = NULL;
956   g_free (encoder->buffer);
957   encoder->buffer = NULL;
958   g_queue_free (encoder->delay);
959   encoder->delay = NULL;
961   gst_x264_enc_close_encoder (encoder);
963   G_OBJECT_CLASS (parent_class)->finalize (object);
966 /*
967  * gst_x264_enc_parse_options
968  * @encoder: Encoder to which options are assigned
969  * @str: Option string
970  *
971  * Parse option string and assign to x264 parameters
972  *
973  */
974 static gboolean
975 gst_x264_enc_parse_options (GstX264Enc * encoder, const gchar * str)
977   GStrv kvpairs;
978   guint npairs, i;
979   gint parse_result = 0, ret = 0;
980   gchar *options = (gchar *) str;
982   while (*options == ':')
983     options++;
985   kvpairs = g_strsplit (options, ":", 0);
986   npairs = g_strv_length (kvpairs);
988   for (i = 0; i < npairs; i++) {
989     GStrv key_val = g_strsplit (kvpairs[i], "=", 2);
991     parse_result =
992         x264_param_parse (&encoder->x264param, key_val[0], key_val[1]);
994     if (parse_result == X264_PARAM_BAD_NAME) {
995       GST_ERROR_OBJECT (encoder, "Bad name for option %s=%s",
996           key_val[0] ? key_val[0] : "", key_val[1] ? key_val[1] : "");
997     }
998     if (parse_result == X264_PARAM_BAD_VALUE) {
999       GST_ERROR_OBJECT (encoder,
1000           "Bad value for option %s=%s (Note: a NULL value for a non-boolean triggers this)",
1001           key_val[0] ? key_val[0] : "", key_val[1] ? key_val[1] : "");
1002     }
1004     g_strfreev (key_val);
1006     if (parse_result)
1007       ret++;
1008   }
1010   g_strfreev (kvpairs);
1011   return !ret;
1014 /*
1015  * gst_x264_enc_init_encoder
1016  * @encoder:  Encoder which should be initialized.
1017  *
1018  * Initialize x264 encoder.
1019  *
1020  */
1021 static gboolean
1022 gst_x264_enc_init_encoder (GstX264Enc * encoder)
1024   guint pass = 0;
1026   /* make sure that the encoder is closed */
1027   gst_x264_enc_close_encoder (encoder);
1029   GST_OBJECT_LOCK (encoder);
1031 #ifdef X264_PRESETS
1032   gst_x264_enc_build_tunings_string (encoder);
1034   /* set x264 parameters and use preset/tuning if present */
1035   GST_DEBUG_OBJECT (encoder, "Applying defaults with preset %s, tunings %s",
1036       encoder->speed_preset ? x264_preset_names[encoder->speed_preset - 1] : "",
1037       encoder->tunings && encoder->tunings->len ? encoder->tunings->str : "");
1038   x264_param_default_preset (&encoder->x264param,
1039       encoder->speed_preset ? x264_preset_names[encoder->speed_preset -
1040           1] : NULL, encoder->tunings
1041       && encoder->tunings->len ? encoder->tunings->str : NULL);
1043   /* log callback setup; part of parameters
1044    * this needs to be done again after every *param_default* () call */
1045   encoder->x264param.pf_log = gst_x264_enc_log_callback;
1046   encoder->x264param.p_log_private = encoder;
1047   encoder->x264param.i_log_level = X264_LOG_DEBUG;
1049   /* if no preset nor tuning, use property defaults */
1050   if (!encoder->speed_preset && !encoder->tunings->len) {
1051 #endif /* X264_PRESETS */
1052     GST_DEBUG_OBJECT (encoder, "Applying x264enc_defaults");
1053     if (x264enc_defaults->len
1054         && gst_x264_enc_parse_options (encoder,
1055             x264enc_defaults->str) == FALSE) {
1056       GST_DEBUG_OBJECT (encoder,
1057           "x264enc_defaults string contains errors. This is a bug.");
1058       goto unlock_and_return;
1059     }
1060 #ifdef X264_PRESETS
1061   } else {
1062     /* When using presets we need to respect the default output format */
1063     encoder->x264param.b_aud = encoder->au_nalu;
1064     encoder->x264param.b_annexb = encoder->byte_stream;
1065   }
1066 #endif /* X264_PRESETS */
1068 #if X264_BUILD >= 81
1069   /* setup appropriate timebase for gstreamer */
1070   encoder->x264param.i_timebase_num = 1;
1071   encoder->x264param.i_timebase_den = 1000000000;
1072 #endif
1074   /* apply option-string property */
1075   if (encoder->option_string_prop && encoder->option_string_prop->len) {
1076     GST_DEBUG_OBJECT (encoder, "Applying option-string: %s",
1077         encoder->option_string_prop->str);
1078     if (gst_x264_enc_parse_options (encoder,
1079             encoder->option_string_prop->str) == FALSE) {
1080       GST_DEBUG_OBJECT (encoder, "Your option-string contains errors.");
1081       goto unlock_and_return;
1082     }
1083   }
1084   /* apply user-set options */
1085   if (encoder->option_string && encoder->option_string->len) {
1086     GST_DEBUG_OBJECT (encoder, "Applying user-set options: %s",
1087         encoder->option_string->str);
1088     if (gst_x264_enc_parse_options (encoder,
1089             encoder->option_string->str) == FALSE) {
1090       GST_DEBUG_OBJECT (encoder, "Failed to parse internal option string. "
1091           "This could be due to use of an old libx264 version. Option string "
1092           "was: %s", encoder->option_string->str);
1093     }
1094   }
1096   /* set up encoder parameters */
1097   encoder->x264param.i_fps_num = encoder->fps_num;
1098   encoder->x264param.i_fps_den = encoder->fps_den;
1099   encoder->x264param.i_width = encoder->width;
1100   encoder->x264param.i_height = encoder->height;
1101   if (encoder->par_den > 0) {
1102     encoder->x264param.vui.i_sar_width = encoder->par_num;
1103     encoder->x264param.vui.i_sar_height = encoder->par_den;
1104   }
1105   /* FIXME 0.11 : 2s default keyframe interval seems excessive
1106    * (10s is x264 default) */
1107   encoder->x264param.i_keyint_max = encoder->keyint_max ? encoder->keyint_max :
1108       (2 * encoder->fps_num / encoder->fps_den);
1110   if ((((encoder->height == 576) && ((encoder->width == 720)
1111                   || (encoder->width == 704) || (encoder->width == 352)))
1112           || ((encoder->height == 288) && (encoder->width == 352)))
1113       && (encoder->fps_den == 1) && (encoder->fps_num == 25)) {
1114     encoder->x264param.vui.i_vidformat = 1;     /* PAL */
1115   } else if ((((encoder->height == 480) && ((encoder->width == 720)
1116                   || (encoder->width == 704) || (encoder->width == 352)))
1117           || ((encoder->height == 240) && (encoder->width == 352)))
1118       && (encoder->fps_den == 1001) && ((encoder->fps_num == 30000)
1119           || (encoder->fps_num == 24000))) {
1120     encoder->x264param.vui.i_vidformat = 2;     /* NTSC */
1121   } else
1122     encoder->x264param.vui.i_vidformat = 5;     /* unspecified */
1124   encoder->x264param.analyse.b_psnr = 0;
1126   switch (encoder->pass) {
1127     case GST_X264_ENC_PASS_QUANT:
1128       encoder->x264param.rc.i_rc_method = X264_RC_CQP;
1129       encoder->x264param.rc.i_qp_constant = encoder->quantizer;
1130       break;
1131     case GST_X264_ENC_PASS_QUAL:
1132       encoder->x264param.rc.i_rc_method = X264_RC_CRF;
1133       encoder->x264param.rc.f_rf_constant = encoder->quantizer;
1134       encoder->x264param.rc.i_vbv_max_bitrate = encoder->bitrate;
1135       encoder->x264param.rc.i_vbv_buffer_size
1136           = encoder->x264param.rc.i_vbv_max_bitrate
1137           * encoder->vbv_buf_capacity / 1000;
1138       break;
1139     case GST_X264_ENC_PASS_CBR:
1140     case GST_X264_ENC_PASS_PASS1:
1141     case GST_X264_ENC_PASS_PASS2:
1142     case GST_X264_ENC_PASS_PASS3:
1143     default:
1144       encoder->x264param.rc.i_rc_method = X264_RC_ABR;
1145       encoder->x264param.rc.i_bitrate = encoder->bitrate;
1146       encoder->x264param.rc.i_vbv_max_bitrate = encoder->bitrate;
1147       encoder->x264param.rc.i_vbv_buffer_size
1148           = encoder->x264param.rc.i_vbv_max_bitrate
1149           * encoder->vbv_buf_capacity / 1000;
1150       pass = encoder->pass & 0xF;
1151       break;
1152   }
1154   switch (pass) {
1155     case 0:
1156       encoder->x264param.rc.b_stat_read = 0;
1157       encoder->x264param.rc.b_stat_write = 0;
1158       break;
1159     case 1:
1160       encoder->x264param.rc.b_stat_read = 0;
1161       encoder->x264param.rc.b_stat_write = 1;
1162 #ifdef X264_PRESETS
1163       x264_param_apply_fastfirstpass (&encoder->x264param);
1164 #else
1165       encoder->x264param.i_frame_reference = 1;
1166       encoder->x264param.analyse.b_transform_8x8 = 0;
1167       encoder->x264param.analyse.inter = 0;
1168       encoder->x264param.analyse.i_me_method = X264_ME_DIA;
1169       encoder->x264param.analyse.i_subpel_refine =
1170           MIN (2, encoder->x264param.analyse.i_subpel_refine);
1171       encoder->x264param.analyse.i_trellis = 0;
1172       encoder->x264param.analyse.b_fast_pskip = 1;
1173 #endif /* X264_PRESETS */
1174       break;
1175     case 2:
1176       encoder->x264param.rc.b_stat_read = 1;
1177       encoder->x264param.rc.b_stat_write = 0;
1178       break;
1179     case 3:
1180       encoder->x264param.rc.b_stat_read = 1;
1181       encoder->x264param.rc.b_stat_write = 1;
1182       break;
1183   }
1185 #if X264_BUILD >= 81 && X264_BUILD < 106
1186   /* When vfr is disabled, libx264 ignores buffer timestamps. This causes
1187    * issues with rate control in libx264 with our nanosecond timebase. This
1188    * has been fixed upstream in libx264 but this workaround is required for
1189    * pre-fix versions. */
1190   if (!encoder->x264param.b_vfr_input) {
1191     if (encoder->x264param.i_fps_num == 0) {
1192       GST_ELEMENT_ERROR (encoder, STREAM, ENCODE,
1193           ("Constant framerate is required."),
1194           ("The framerate caps (%d/%d) indicate VFR but VFR is disabled in libx264. (Is the zerolatency tuning in use?)",
1195               encoder->x264param.i_fps_num, encoder->x264param.i_fps_den));
1196       return FALSE;
1197     }
1198     encoder->x264param.i_timebase_num = encoder->x264param.i_fps_den;
1199     encoder->x264param.i_timebase_den = encoder->x264param.i_fps_num;
1200   }
1201 #endif
1203 #ifdef X264_PRESETS
1204   if (encoder->profile
1205       && x264_param_apply_profile (&encoder->x264param,
1206           x264_profile_names[encoder->profile - 1])) {
1207     GST_WARNING_OBJECT (encoder, "Bad profile name: %s",
1208         x264_profile_names[encoder->profile - 1]);
1209   }
1210 #endif /* X264_PRESETS */
1212   GST_OBJECT_UNLOCK (encoder);
1214   encoder->x264enc = x264_encoder_open (&encoder->x264param);
1215   if (!encoder->x264enc) {
1216     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE,
1217         ("Can not initialize x264 encoder."), (NULL));
1218     return FALSE;
1219   }
1221   return TRUE;
1223 unlock_and_return:
1224   GST_OBJECT_UNLOCK (encoder);
1225   return FALSE;
1228 /* gst_x264_enc_close_encoder
1229  * @encoder:  Encoder which should close.
1230  *
1231  * Close x264 encoder.
1232  */
1233 static void
1234 gst_x264_enc_close_encoder (GstX264Enc * encoder)
1236   if (encoder->x264enc != NULL) {
1237     x264_encoder_close (encoder->x264enc);
1238     encoder->x264enc = NULL;
1239   }
1242 /*
1243  * Returns: Buffer with the stream headers.
1244  */
1245 static GstBuffer *
1246 gst_x264_enc_header_buf (GstX264Enc * encoder)
1248   GstBuffer *buf;
1249   x264_nal_t *nal;
1250   int i_nal;
1251   int header_return;
1252   int i_size;
1253   int nal_size;
1254 #ifndef X264_ENC_NALS
1255   int i_data;
1256 #endif
1257   guint8 *buffer, *sps;
1258   gulong buffer_size;
1259   gint sei_ni = 2, sps_ni = 0, pps_ni = 1;
1261   if (G_UNLIKELY (encoder->x264enc == NULL))
1262     return NULL;
1264   /* Create avcC header. */
1266   header_return = x264_encoder_headers (encoder->x264enc, &nal, &i_nal);
1267   if (header_return < 0) {
1268     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE, ("Encode x264 header failed."),
1269         ("x264_encoder_headers return code=%d", header_return));
1270     return NULL;
1271   }
1273   /* old x264 returns SEI, SPS and PPS, newer one has SEI last */
1274   if (i_nal == 3 && nal[sps_ni].i_type != 7) {
1275     sei_ni = 0;
1276     sps_ni = 1;
1277     pps_ni = 2;
1278   }
1280   /* x264 is expected to return an SEI (some identification info),
1281    * and SPS and PPS */
1282   if (i_nal != 3 || nal[sps_ni].i_type != 7 || nal[pps_ni].i_type != 8 ||
1283       nal[sps_ni].i_payload < 4 || nal[pps_ni].i_payload < 1) {
1284     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE, (NULL),
1285         ("Unexpected x264 header."));
1286     return NULL;
1287   }
1289   GST_MEMDUMP ("SEI", nal[sei_ni].p_payload, nal[sei_ni].i_payload);
1290   GST_MEMDUMP ("SPS", nal[sps_ni].p_payload, nal[sps_ni].i_payload);
1291   GST_MEMDUMP ("PPS", nal[pps_ni].p_payload, nal[pps_ni].i_payload);
1293   /* nal payloads with emulation_prevention_three_byte, and some header data */
1294   buffer_size = (nal[sps_ni].i_payload + nal[pps_ni].i_payload) * 4 + 100;
1295   buffer = g_malloc (buffer_size);
1297   /* old style API: nal's are not encapsulated, and have no sync/size prefix,
1298    * new style API: nal's are encapsulated, and have 4-byte size prefix */
1299 #ifndef X264_ENC_NALS
1300   sps = nal[sps_ni].p_payload;
1301 #else
1302   sps = nal[sps_ni].p_payload + 4;
1303   /* skip NAL unit type */
1304   sps++;
1305 #endif
1307   buffer[0] = 1;                /* AVC Decoder Configuration Record ver. 1 */
1308   buffer[1] = sps[0];           /* profile_idc                             */
1309   buffer[2] = sps[1];           /* profile_compability                     */
1310   buffer[3] = sps[2];           /* level_idc                               */
1311   buffer[4] = 0xfc | (4 - 1);   /* nal_length_size_minus1                  */
1313   i_size = 5;
1315   buffer[i_size++] = 0xe0 | 1;  /* number of SPSs */
1317 #ifndef X264_ENC_NALS
1318   i_data = buffer_size - i_size - 2;
1319   nal_size = x264_nal_encode (buffer + i_size + 2, &i_data, 0, &nal[sps_ni]);
1320 #else
1321   nal_size = nal[sps_ni].i_payload - 4;
1322   memcpy (buffer + i_size + 2, nal[sps_ni].p_payload + 4, nal_size);
1323 #endif
1324   GST_WRITE_UINT16_BE (buffer + i_size, nal_size);
1325   i_size += nal_size + 2;
1327   buffer[i_size++] = 1;         /* number of PPSs */
1329 #ifndef X264_ENC_NALS
1330   i_data = buffer_size - i_size - 2;
1331   nal_size = x264_nal_encode (buffer + i_size + 2, &i_data, 0, &nal[pps_ni]);
1332 #else
1333   nal_size = nal[pps_ni].i_payload - 4;
1334   memcpy (buffer + i_size + 2, nal[pps_ni].p_payload + 4, nal_size);
1335 #endif
1336   GST_WRITE_UINT16_BE (buffer + i_size, nal_size);
1337   i_size += nal_size + 2;
1339   buf = gst_buffer_new_and_alloc (i_size);
1340   memcpy (GST_BUFFER_DATA (buf), buffer, i_size);
1341   g_free (buffer);
1343   GST_MEMDUMP ("header", GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1345   return buf;
1348 /* gst_x264_enc_set_src_caps
1349  * Returns: TRUE on success.
1350  */
1351 static gboolean
1352 gst_x264_enc_set_src_caps (GstX264Enc * encoder, GstPad * pad, GstCaps * caps)
1354   GstBuffer *buf;
1355   GstCaps *outcaps;
1356   GstStructure *structure;
1357   gboolean res;
1359   outcaps = gst_caps_new_simple ("video/x-h264",
1360       "width", G_TYPE_INT, encoder->width,
1361       "height", G_TYPE_INT, encoder->height,
1362       "framerate", GST_TYPE_FRACTION, encoder->fps_num, encoder->fps_den,
1363       "pixel-aspect-ratio", GST_TYPE_FRACTION, encoder->par_num,
1364       encoder->par_den, NULL);
1366   structure = gst_caps_get_structure (outcaps, 0);
1368   if (!encoder->byte_stream) {
1369     buf = gst_x264_enc_header_buf (encoder);
1370     if (buf != NULL) {
1371       gst_caps_set_simple (outcaps, "codec_data", GST_TYPE_BUFFER, buf, NULL);
1372       gst_buffer_unref (buf);
1373     }
1374     gst_structure_set (structure, "stream-format", G_TYPE_STRING, "avc", NULL);
1375   } else {
1376     gst_structure_set (structure, "stream-format", G_TYPE_STRING, "byte-stream",
1377         NULL);
1378   }
1379   gst_structure_set (structure, "alignment", G_TYPE_STRING, "au", NULL);
1381   res = gst_pad_set_caps (pad, outcaps);
1382   gst_caps_unref (outcaps);
1384   return res;
1387 static gboolean
1388 gst_x264_enc_sink_set_caps (GstPad * pad, GstCaps * caps)
1390   GstX264Enc *encoder = GST_X264_ENC (GST_OBJECT_PARENT (pad));
1391   GstVideoFormat format;
1392   gint width, height;
1393   gint fps_num, fps_den;
1394   gint par_num, par_den;
1395   gint i;
1397   /* get info from caps */
1398   if (!gst_video_format_parse_caps (caps, &format, &width, &height))
1399     return FALSE;
1400   if (!gst_video_parse_caps_framerate (caps, &fps_num, &fps_den))
1401     return FALSE;
1402   if (!gst_video_parse_caps_pixel_aspect_ratio (caps, &par_num, &par_den)) {
1403     par_num = 1;
1404     par_den = 1;
1405   }
1407   /* If the encoder is initialized, do not reinitialize it again if not
1408    * necessary */
1409   if (encoder->x264enc) {
1410     if (width == encoder->width && height == encoder->height
1411         && fps_num == encoder->fps_num && fps_den == encoder->fps_den
1412         && par_num == encoder->par_num && par_den == encoder->par_den)
1413       return TRUE;
1415     /* clear out pending frames */
1416     gst_x264_enc_flush_frames (encoder, TRUE);
1418     encoder->sps_id++;
1419   }
1421   /* store input description */
1422   encoder->format = format;
1423   encoder->width = width;
1424   encoder->height = height;
1425   encoder->fps_num = fps_num;
1426   encoder->fps_den = fps_den;
1427   encoder->par_num = par_num;
1428   encoder->par_den = par_den;
1430   /* prepare a cached image description */
1431   encoder->image_size = gst_video_format_get_size (encoder->format, width,
1432       height);
1433   for (i = 0; i < 3; ++i) {
1434     /* only offsets now, is shifted later. Offsets will be for Y, U, V so we
1435      * can just feed YV12 as I420 to the decoder later */
1436     encoder->offset[i] = gst_video_format_get_component_offset (encoder->format,
1437         i, width, height);
1438     encoder->stride[i] = gst_video_format_get_row_stride (encoder->format,
1439         i, width);
1440   }
1442   if (!gst_x264_enc_init_encoder (encoder))
1443     return FALSE;
1445   if (!gst_x264_enc_set_src_caps (encoder, encoder->srcpad, caps)) {
1446     gst_x264_enc_close_encoder (encoder);
1447     return FALSE;
1448   }
1450   return TRUE;
1453 static gboolean
1454 gst_x264_enc_src_event (GstPad * pad, GstEvent * event)
1456   gboolean ret = TRUE;
1457   GstX264Enc *encoder;
1458   gboolean forward = TRUE;
1460   encoder = GST_X264_ENC (gst_pad_get_parent (pad));
1462   switch (GST_EVENT_TYPE (event)) {
1463     case GST_EVENT_CUSTOM_UPSTREAM:{
1464       const GstStructure *s;
1465       s = gst_event_get_structure (event);
1466       if (gst_structure_has_name (s, "GstForceKeyUnit")) {
1467         /* Set I frame request */
1468         GST_OBJECT_LOCK (encoder);
1469         encoder->i_type = X264_TYPE_I;
1470         encoder->forcekeyunit_event = gst_event_copy (event);
1471         GST_EVENT_TYPE (encoder->forcekeyunit_event) =
1472             GST_EVENT_CUSTOM_DOWNSTREAM;
1473         GST_OBJECT_UNLOCK (encoder);
1474         forward = FALSE;
1475         gst_event_unref (event);
1476       }
1477       break;
1478     }
1479     default:
1480       break;
1481   }
1483   if (forward)
1484     ret = gst_pad_push_event (encoder->sinkpad, event);
1486   gst_object_unref (encoder);
1487   return ret;
1490 static gboolean
1491 gst_x264_enc_sink_event (GstPad * pad, GstEvent * event)
1493   gboolean ret;
1494   GstX264Enc *encoder;
1496   encoder = GST_X264_ENC (gst_pad_get_parent (pad));
1498   switch (GST_EVENT_TYPE (event)) {
1499     case GST_EVENT_EOS:
1500       gst_x264_enc_flush_frames (encoder, TRUE);
1501       break;
1502     case GST_EVENT_TAG:{
1503       GstTagList *tags = NULL;
1505       event =
1506           GST_EVENT (gst_mini_object_make_writable (GST_MINI_OBJECT (event)));
1508       gst_event_parse_tag (event, &tags);
1509       /* drop codec/video-codec and replace encoder/encoder-version */
1510       gst_tag_list_remove_tag (tags, GST_TAG_VIDEO_CODEC);
1511       gst_tag_list_remove_tag (tags, GST_TAG_CODEC);
1512       gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_ENCODER, "x264",
1513           GST_TAG_ENCODER_VERSION, X264_BUILD, NULL);
1514       /* push is done below */
1515       break;
1516       /* no flushing if flush received,
1517        * buffers in encoder are considered (in the) past */
1518     }
1519     case GST_EVENT_CUSTOM_DOWNSTREAM:{
1520       const GstStructure *s;
1521       s = gst_event_get_structure (event);
1522       if (gst_structure_has_name (s, "GstForceKeyUnit")) {
1523         GST_OBJECT_LOCK (encoder);
1524         encoder->i_type = X264_TYPE_I;
1525         GST_OBJECT_UNLOCK (encoder);
1526       }
1527       break;
1528     }
1529     default:
1530       break;
1531   }
1533   ret = gst_pad_push_event (encoder->srcpad, event);
1535   gst_object_unref (encoder);
1536   return ret;
1539 /* chain function
1540  * this function does the actual processing
1541  */
1542 static GstFlowReturn
1543 gst_x264_enc_chain (GstPad * pad, GstBuffer * buf)
1545   GstX264Enc *encoder = GST_X264_ENC (GST_OBJECT_PARENT (pad));
1546   GstFlowReturn ret;
1547   x264_picture_t pic_in;
1548   gint i_nal, i;
1549   if (G_UNLIKELY (encoder->x264enc == NULL))
1550     goto not_inited;
1552   /* create x264_picture_t from the buffer */
1553   /* mostly taken from mplayer (file ve_x264.c) */
1554   if (G_UNLIKELY (GST_BUFFER_SIZE (buf) < encoder->image_size))
1555     goto wrong_buffer_size;
1557   /* remember the timestamp and duration */
1558   g_queue_push_tail (encoder->delay, buf);
1560   /* set up input picture */
1561   memset (&pic_in, 0, sizeof (pic_in));
1563   pic_in.img.i_csp = X264_CSP_I420;
1564   pic_in.img.i_plane = 3;
1565   for (i = 0; i < 3; i++) {
1566     pic_in.img.plane[i] = GST_BUFFER_DATA (buf) + encoder->offset[i];
1567     pic_in.img.i_stride[i] = encoder->stride[i];
1568   }
1570   GST_OBJECT_LOCK (encoder);
1571   pic_in.i_type = encoder->i_type;
1573   /* Reset encoder forced picture type */
1574   encoder->i_type = X264_TYPE_AUTO;
1575   GST_OBJECT_UNLOCK (encoder);
1577   pic_in.i_pts = GST_BUFFER_TIMESTAMP (buf);
1579   ret = gst_x264_enc_encode_frame (encoder, &pic_in, &i_nal, TRUE);
1581   /* input buffer is released later on */
1582   return ret;
1584 /* ERRORS */
1585 not_inited:
1586   {
1587     GST_WARNING_OBJECT (encoder, "Got buffer before set_caps was called");
1588     gst_buffer_unref (buf);
1589     return GST_FLOW_NOT_NEGOTIATED;
1590   }
1591 wrong_buffer_size:
1592   {
1593     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE,
1594         ("Encode x264 frame failed."),
1595         ("Wrong buffer size %d (should be %d)",
1596             GST_BUFFER_SIZE (buf), encoder->image_size));
1597     gst_buffer_unref (buf);
1598     return GST_FLOW_ERROR;
1599   }
1602 static GstFlowReturn
1603 gst_x264_enc_encode_frame (GstX264Enc * encoder, x264_picture_t * pic_in,
1604     int *i_nal, gboolean send)
1606   GstBuffer *out_buf = NULL, *in_buf = NULL;
1607   x264_picture_t pic_out;
1608   x264_nal_t *nal;
1609   int i_size;
1610 #ifndef X264_ENC_NALS
1611   int nal_size;
1612   gint i;
1613 #endif
1614   int encoder_return;
1615   GstFlowReturn ret;
1616   GstClockTime timestamp;
1617   GstClockTime duration;
1618   guint8 *data;
1619   GstEvent *forcekeyunit_event = NULL;
1621   if (G_UNLIKELY (encoder->x264enc == NULL))
1622     return GST_FLOW_NOT_NEGOTIATED;
1624   encoder_return = x264_encoder_encode (encoder->x264enc,
1625       &nal, i_nal, pic_in, &pic_out);
1627   if (encoder_return < 0) {
1628     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE, ("Encode x264 frame failed."),
1629         ("x264_encoder_encode return code=%d", encoder_return));
1630     return GST_FLOW_ERROR;
1631   }
1633   if (!*i_nal) {
1634     return GST_FLOW_OK;
1635   }
1636 #ifndef X264_ENC_NALS
1637   i_size = 0;
1638   for (i = 0; i < *i_nal; i++) {
1639     gint i_data = encoder->buffer_size - i_size - 4;
1641     if (i_data < nal[i].i_payload * 2) {
1642       encoder->buffer_size += 2 * nal[i].i_payload;
1643       encoder->buffer = g_realloc (encoder->buffer, encoder->buffer_size);
1644       i_data = encoder->buffer_size - i_size - 4;
1645     }
1647     nal_size =
1648         x264_nal_encode (encoder->buffer + i_size + 4, &i_data, 0, &nal[i]);
1649     if (encoder->byte_stream)
1650       GST_WRITE_UINT32_BE (encoder->buffer + i_size, 1);
1651     else
1652       GST_WRITE_UINT32_BE (encoder->buffer + i_size, nal_size);
1654     i_size += nal_size + 4;
1655   }
1656   data = encoder->buffer;
1657 #else
1658   i_size = encoder_return;
1659   data = nal[0].p_payload;
1660 #endif
1662   in_buf = g_queue_pop_head (encoder->delay);
1663   if (in_buf) {
1664     timestamp = GST_BUFFER_TIMESTAMP (in_buf);
1665     duration = GST_BUFFER_DURATION (in_buf);
1666     gst_buffer_unref (in_buf);
1667   } else {
1668     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE, (NULL),
1669         ("Timestamp queue empty."));
1670     return GST_FLOW_ERROR;
1671   }
1673   if (!send)
1674     return GST_FLOW_OK;
1676   ret = gst_pad_alloc_buffer (encoder->srcpad, GST_BUFFER_OFFSET_NONE,
1677       i_size, GST_PAD_CAPS (encoder->srcpad), &out_buf);
1678   if (ret != GST_FLOW_OK)
1679     return ret;
1681   memcpy (GST_BUFFER_DATA (out_buf), data, i_size);
1682   GST_BUFFER_SIZE (out_buf) = i_size;
1684   /* PTS */
1685   /* FIXME ??: maybe use DTS here, since:
1686    * - it is so practiced by other encoders,
1687    * - downstream (e.g. muxers) might not enjoy non-monotone timestamps,
1688    *   whereas a decoder can also deal with DTS */
1689   GST_BUFFER_TIMESTAMP (out_buf) = pic_out.i_pts;
1690   GST_BUFFER_DURATION (out_buf) = duration;
1692 #ifdef X264_INTRA_REFRESH
1693   if (pic_out.b_keyframe) {
1694 #else
1695   if (pic_out.i_type == X264_TYPE_IDR) {
1696 #endif
1697     GST_BUFFER_FLAG_UNSET (out_buf, GST_BUFFER_FLAG_DELTA_UNIT);
1698   } else {
1699     GST_BUFFER_FLAG_SET (out_buf, GST_BUFFER_FLAG_DELTA_UNIT);
1700   }
1702   GST_OBJECT_LOCK (encoder);
1703   forcekeyunit_event = encoder->forcekeyunit_event;
1704   encoder->forcekeyunit_event = NULL;
1705   GST_OBJECT_UNLOCK (encoder);
1706   if (forcekeyunit_event) {
1707     gst_structure_set (forcekeyunit_event->structure,
1708         "timestamp", G_TYPE_UINT64, GST_BUFFER_TIMESTAMP (out_buf), NULL);
1709     gst_pad_push_event (encoder->srcpad, forcekeyunit_event);
1710   }
1712   return gst_pad_push (encoder->srcpad, out_buf);
1715 static void
1716 gst_x264_enc_flush_frames (GstX264Enc * encoder, gboolean send)
1718   GstFlowReturn flow_ret;
1719   gint i_nal;
1721   /* first send the remaining frames */
1722   if (encoder->x264enc)
1723     do {
1724       flow_ret = gst_x264_enc_encode_frame (encoder, NULL, &i_nal, send);
1725 #ifdef X264_DELAYED_FRAMES_API
1726     } while (flow_ret == GST_FLOW_OK
1727         && x264_encoder_delayed_frames (encoder->x264enc) > 0);
1728 #else
1729       /* note that this doesn't flush all frames for > 1 delayed frame */
1730     } while (flow_ret == GST_FLOW_OK && i_nal > 0);
1731 #endif
1733   /* in any case, make sure the delay queue is emptied */
1734   while (!g_queue_is_empty (encoder->delay))
1735     gst_buffer_unref (g_queue_pop_head (encoder->delay));
1738 static GstStateChangeReturn
1739 gst_x264_enc_change_state (GstElement * element, GstStateChange transition)
1741   GstX264Enc *encoder = GST_X264_ENC (element);
1742   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1744   ret = parent_class->change_state (element, transition);
1745   if (ret == GST_STATE_CHANGE_FAILURE)
1746     goto out;
1748   switch (transition) {
1749     case GST_STATE_CHANGE_PAUSED_TO_READY:
1750       gst_x264_enc_flush_frames (encoder, FALSE);
1751       gst_x264_enc_close_encoder (encoder);
1752       gst_x264_enc_reset (encoder);
1753       break;
1754     default:
1755       break;
1756   }
1758 out:
1759   return ret;
1762 static void
1763 gst_x264_enc_set_property (GObject * object, guint prop_id,
1764     const GValue * value, GParamSpec * pspec)
1766   GstX264Enc *encoder;
1767   GstState state;
1769   const gchar *partitions = NULL;
1771   encoder = GST_X264_ENC (object);
1773   GST_OBJECT_LOCK (encoder);
1774   /* state at least matters for sps, bytestream, pass,
1775    * and so by extension ... */
1776   state = GST_STATE (encoder);
1777   if (state != GST_STATE_READY && state != GST_STATE_NULL)
1778     goto wrong_state;
1780   switch (prop_id) {
1781     case ARG_PASS:
1782       encoder->pass = g_value_get_enum (value);
1783       break;
1784     case ARG_QUANTIZER:
1785       encoder->quantizer = g_value_get_uint (value);
1786       break;
1787     case ARG_BITRATE:
1788       encoder->bitrate = g_value_get_uint (value);
1789       break;
1790     case ARG_VBV_BUF_CAPACITY:
1791       encoder->vbv_buf_capacity = g_value_get_uint (value);
1792       break;
1793     case ARG_SPEED_PRESET:
1794       encoder->speed_preset = g_value_get_enum (value);
1795       break;
1796     case ARG_PSY_TUNE:
1797       encoder->psy_tune = g_value_get_enum (value);
1798       break;
1799     case ARG_TUNE:
1800       encoder->tune = g_value_get_flags (value);
1801       break;
1802     case ARG_PROFILE:
1803       encoder->profile = g_value_get_enum (value);
1804       break;
1805     case ARG_OPTION_STRING:
1806       g_string_assign (encoder->option_string_prop, g_value_get_string (value));
1807       break;
1808     case ARG_THREADS:
1809       encoder->threads = g_value_get_uint (value);
1810       g_string_append_printf (encoder->option_string, ":threads=%d",
1811           encoder->threads);
1812       break;
1813     case ARG_SLICED_THREADS:
1814       encoder->sliced_threads = g_value_get_boolean (value);
1815       g_string_append_printf (encoder->option_string, ":sliced-threads=%d",
1816           encoder->sliced_threads);
1817       break;
1818     case ARG_SYNC_LOOKAHEAD:
1819       encoder->sync_lookahead = g_value_get_int (value);
1820       g_string_append_printf (encoder->option_string, ":sync-lookahead=%d",
1821           encoder->sync_lookahead);
1822       break;
1823     case ARG_STATS_FILE:
1824     case ARG_MULTIPASS_CACHE_FILE:
1825       if (encoder->mp_cache_file)
1826         g_free (encoder->mp_cache_file);
1827       encoder->mp_cache_file = g_value_dup_string (value);
1828       g_string_append_printf (encoder->option_string, ":stats=%s",
1829           encoder->mp_cache_file);
1830       break;
1831     case ARG_BYTE_STREAM:
1832       encoder->byte_stream = g_value_get_boolean (value);
1833       g_string_append_printf (encoder->option_string, ":annexb=%d",
1834           encoder->byte_stream);
1835       break;
1836     case ARG_INTRA_REFRESH:
1837       encoder->intra_refresh = g_value_get_boolean (value);
1838       g_string_append_printf (encoder->option_string, ":intra-refresh=%d",
1839           encoder->intra_refresh);
1840       break;
1841     case ARG_ME:
1842       encoder->me = g_value_get_enum (value);
1843       g_string_append_printf (encoder->option_string, ":me=%s",
1844           x264_motion_est_names[encoder->me]);
1845       break;
1846     case ARG_SUBME:
1847       encoder->subme = g_value_get_uint (value);
1848       g_string_append_printf (encoder->option_string, ":subme=%d",
1849           encoder->subme);
1850       break;
1851     case ARG_ANALYSE:
1852       encoder->analyse = g_value_get_flags (value);
1853       partitions = gst_x264_enc_build_partitions (encoder->analyse);
1854       if (partitions) {
1855         g_string_append_printf (encoder->option_string, ":partitions=%s",
1856             partitions);
1857         g_free ((gpointer) partitions);
1858       }
1859       break;
1860     case ARG_DCT8x8:
1861       encoder->dct8x8 = g_value_get_boolean (value);
1862       g_string_append_printf (encoder->option_string, ":8x8dct=%d",
1863           encoder->dct8x8);
1864       break;
1865     case ARG_REF:
1866       encoder->ref = g_value_get_uint (value);
1867       g_string_append_printf (encoder->option_string, ":ref=%d", encoder->ref);
1868       break;
1869     case ARG_BFRAMES:
1870       encoder->bframes = g_value_get_uint (value);
1871       g_string_append_printf (encoder->option_string, ":bframes=%d",
1872           encoder->bframes);
1873       break;
1874     case ARG_B_ADAPT:
1875       encoder->b_adapt = g_value_get_boolean (value);
1876       g_string_append_printf (encoder->option_string, ":b-adapt=%d",
1877           encoder->b_adapt);
1878       break;
1879     case ARG_B_PYRAMID:
1880       encoder->b_pyramid = g_value_get_boolean (value);
1881 #ifdef X264_B_PYRAMID
1882       g_string_append_printf (encoder->option_string, ":b-pyramid=%s",
1883           x264_b_pyramid_names[encoder->b_pyramid]);
1884 #else
1885       g_string_append_printf (encoder->option_string, ":b-pyramid=%d",
1886           encoder->b_pyramid);
1887 #endif /* X264_B_PYRAMID */
1888       break;
1889     case ARG_WEIGHTB:
1890       encoder->weightb = g_value_get_boolean (value);
1891       g_string_append_printf (encoder->option_string, ":weightb=%d",
1892           encoder->weightb);
1893       break;
1894     case ARG_SPS_ID:
1895       encoder->sps_id = g_value_get_uint (value);
1896       g_string_append_printf (encoder->option_string, ":sps-id=%d",
1897           encoder->sps_id);
1898       break;
1899     case ARG_AU_NALU:
1900       encoder->au_nalu = g_value_get_boolean (value);
1901       g_string_append_printf (encoder->option_string, ":aud=%d",
1902           encoder->au_nalu);
1903       break;
1904     case ARG_TRELLIS:
1905       encoder->trellis = g_value_get_boolean (value);
1906       g_string_append_printf (encoder->option_string, ":trellis=%d",
1907           encoder->trellis);
1908       break;
1909     case ARG_KEYINT_MAX:
1910       encoder->keyint_max = g_value_get_uint (value);
1911       g_string_append_printf (encoder->option_string, ":keyint=%d",
1912           encoder->keyint_max);
1913       break;
1914     case ARG_CABAC:
1915       encoder->cabac = g_value_get_boolean (value);
1916       g_string_append_printf (encoder->option_string, ":cabac=%d",
1917           encoder->cabac);
1918       break;
1919     case ARG_QP_MIN:
1920       encoder->qp_min = g_value_get_uint (value);
1921       g_string_append_printf (encoder->option_string, ":qpmin=%d",
1922           encoder->qp_min);
1923       break;
1924     case ARG_QP_MAX:
1925       encoder->qp_max = g_value_get_uint (value);
1926       g_string_append_printf (encoder->option_string, ":qpmax=%d",
1927           encoder->qp_max);
1928       break;
1929     case ARG_QP_STEP:
1930       encoder->qp_step = g_value_get_uint (value);
1931       g_string_append_printf (encoder->option_string, ":qpstep=%d",
1932           encoder->qp_step);
1933       break;
1934     case ARG_IP_FACTOR:
1935       encoder->ip_factor = g_value_get_float (value);
1936       g_string_append_printf (encoder->option_string, ":ip-factor=%f",
1937           encoder->ip_factor);
1938       break;
1939     case ARG_PB_FACTOR:
1940       encoder->pb_factor = g_value_get_float (value);
1941       g_string_append_printf (encoder->option_string, ":pb-factor=%f",
1942           encoder->pb_factor);
1943       break;
1944     case ARG_RC_MB_TREE:
1945       encoder->mb_tree = g_value_get_boolean (value);
1946       g_string_append_printf (encoder->option_string, ":mbtree=%d",
1947           encoder->mb_tree);
1948       break;
1949     case ARG_RC_LOOKAHEAD:
1950       encoder->rc_lookahead = g_value_get_int (value);
1951       g_string_append_printf (encoder->option_string, ":rc-lookahead=%d",
1952           encoder->rc_lookahead);
1953       break;
1954     case ARG_NR:
1955       encoder->noise_reduction = g_value_get_uint (value);
1956       g_string_append_printf (encoder->option_string, ":nr=%d",
1957           encoder->noise_reduction);
1958       break;
1959     case ARG_INTERLACED:
1960       encoder->interlaced = g_value_get_boolean (value);
1961       g_string_append_printf (encoder->option_string, ":interlaced=%d",
1962           encoder->interlaced);
1963       break;
1964     default:
1965       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1966       break;
1967   }
1968   GST_OBJECT_UNLOCK (encoder);
1969   return;
1971   /* ERROR */
1972 wrong_state:
1973   {
1974     GST_DEBUG_OBJECT (encoder, "setting property in wrong state");
1975     GST_OBJECT_UNLOCK (encoder);
1976   }
1979 static void
1980 gst_x264_enc_get_property (GObject * object, guint prop_id,
1981     GValue * value, GParamSpec * pspec)
1983   GstX264Enc *encoder;
1985   encoder = GST_X264_ENC (object);
1987   GST_OBJECT_LOCK (encoder);
1988   switch (prop_id) {
1989     case ARG_THREADS:
1990       g_value_set_uint (value, encoder->threads);
1991       break;
1992     case ARG_SLICED_THREADS:
1993       g_value_set_boolean (value, encoder->sliced_threads);
1994       break;
1995     case ARG_SYNC_LOOKAHEAD:
1996       g_value_set_int (value, encoder->sync_lookahead);
1997       break;
1998     case ARG_PASS:
1999       g_value_set_enum (value, encoder->pass);
2000       break;
2001     case ARG_QUANTIZER:
2002       g_value_set_uint (value, encoder->quantizer);
2003       break;
2004     case ARG_STATS_FILE:
2005     case ARG_MULTIPASS_CACHE_FILE:
2006       g_value_set_string (value, encoder->mp_cache_file);
2007       break;
2008     case ARG_BYTE_STREAM:
2009       g_value_set_boolean (value, encoder->byte_stream);
2010       break;
2011     case ARG_BITRATE:
2012       g_value_set_uint (value, encoder->bitrate);
2013       break;
2014     case ARG_INTRA_REFRESH:
2015       g_value_set_boolean (value, encoder->intra_refresh);
2016       break;
2017     case ARG_VBV_BUF_CAPACITY:
2018       g_value_set_uint (value, encoder->vbv_buf_capacity);
2019       break;
2020     case ARG_ME:
2021       g_value_set_enum (value, encoder->me);
2022       break;
2023     case ARG_SUBME:
2024       g_value_set_uint (value, encoder->subme);
2025       break;
2026     case ARG_ANALYSE:
2027       g_value_set_flags (value, encoder->analyse);
2028       break;
2029     case ARG_DCT8x8:
2030       g_value_set_boolean (value, encoder->dct8x8);
2031       break;
2032     case ARG_REF:
2033       g_value_set_uint (value, encoder->ref);
2034       break;
2035     case ARG_BFRAMES:
2036       g_value_set_uint (value, encoder->bframes);
2037       break;
2038     case ARG_B_ADAPT:
2039       g_value_set_boolean (value, encoder->b_adapt);
2040       break;
2041     case ARG_B_PYRAMID:
2042       g_value_set_boolean (value, encoder->b_pyramid);
2043       break;
2044     case ARG_WEIGHTB:
2045       g_value_set_boolean (value, encoder->weightb);
2046       break;
2047     case ARG_SPS_ID:
2048       g_value_set_uint (value, encoder->sps_id);
2049       break;
2050     case ARG_AU_NALU:
2051       g_value_set_boolean (value, encoder->au_nalu);
2052       break;
2053     case ARG_TRELLIS:
2054       g_value_set_boolean (value, encoder->trellis);
2055       break;
2056     case ARG_KEYINT_MAX:
2057       g_value_set_uint (value, encoder->keyint_max);
2058       break;
2059     case ARG_QP_MIN:
2060       g_value_set_uint (value, encoder->qp_min);
2061       break;
2062     case ARG_QP_MAX:
2063       g_value_set_uint (value, encoder->qp_max);
2064       break;
2065     case ARG_QP_STEP:
2066       g_value_set_uint (value, encoder->qp_step);
2067       break;
2068     case ARG_CABAC:
2069       g_value_set_boolean (value, encoder->cabac);
2070       break;
2071     case ARG_IP_FACTOR:
2072       g_value_set_float (value, encoder->ip_factor);
2073       break;
2074     case ARG_PB_FACTOR:
2075       g_value_set_float (value, encoder->pb_factor);
2076       break;
2077     case ARG_RC_MB_TREE:
2078       g_value_set_boolean (value, encoder->mb_tree);
2079       break;
2080     case ARG_RC_LOOKAHEAD:
2081       g_value_set_int (value, encoder->rc_lookahead);
2082       break;
2083     case ARG_NR:
2084       g_value_set_uint (value, encoder->noise_reduction);
2085       break;
2086     case ARG_INTERLACED:
2087       g_value_set_boolean (value, encoder->interlaced);
2088       break;
2089     case ARG_SPEED_PRESET:
2090       g_value_set_enum (value, encoder->speed_preset);
2091       break;
2092     case ARG_PSY_TUNE:
2093       g_value_set_enum (value, encoder->psy_tune);
2094       break;
2095     case ARG_TUNE:
2096       g_value_set_flags (value, encoder->tune);
2097       break;
2098     case ARG_PROFILE:
2099       g_value_set_enum (value, encoder->profile);
2100       break;
2101     case ARG_OPTION_STRING:
2102       g_value_set_string (value, encoder->option_string_prop->str);
2103       break;
2104     default:
2105       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2106       break;
2107   }
2108   GST_OBJECT_UNLOCK (encoder);
2111 static gboolean
2112 plugin_init (GstPlugin * plugin)
2114   GST_DEBUG_CATEGORY_INIT (x264_enc_debug, "x264enc", 0,
2115       "h264 encoding element");
2117   return gst_element_register (plugin, "x264enc",
2118       GST_RANK_PRIMARY, GST_TYPE_X264_ENC);
2121 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
2122     GST_VERSION_MINOR,
2123     "x264",
2124     "libx264-based H264 plugins",
2125     plugin_init, VERSION, "GPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)