x264enc: Print full option-string applied to x264_encoder in debug log
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-ugly / 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  * Copyright (C) 2016 Sebastian Dröge <sebastian@centricular.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 /**
24  * SECTION:element-x264enc
25  * @title: x264enc
26  * @see_also: faac
27  *
28  * This element encodes raw video into H264 compressed data,
29  * also otherwise known as MPEG-4 AVC (Advanced Video Codec).
30  *
31  * The #GstX264Enc:pass property controls the type of encoding.  In case of Constant
32  * Bitrate Encoding (actually ABR), the #GstX264Enc:bitrate will determine the quality
33  * of the encoding.  This will similarly be the case if this target bitrate
34  * is to obtained in multiple (2 or 3) pass encoding.
35  * Alternatively, one may choose to perform Constant Quantizer or Quality encoding,
36  * in which case the #GstX264Enc:quantizer property controls much of the outcome, in that case #GstX264Enc:bitrate is the maximum bitrate.
37  *
38  * The H264 profile that is eventually used depends on a few settings.
39  * If #GstX264Enc:dct8x8 is enabled, then High profile is used.
40  * Otherwise, if #GstX264Enc:cabac entropy coding is enabled or #GstX264Enc:bframes
41  * are allowed, then Main Profile is in effect, and otherwise Baseline profile
42  * applies.  The high profile is imposed by default,
43  * which is fine for most software players and settings,
44  * but in some cases (e.g. hardware platforms) a more restricted profile/level
45  * may be necessary. The recommended way to set a profile is to set it in the
46  * downstream caps.
47  *
48  * If a preset/tuning are specified then these will define the default values and
49  * the property defaults will be ignored. After this the option-string property is
50  * applied, followed by the user-set properties, fast first pass restrictions and
51  * finally the profile restrictions.
52  *
53  * > Some settings, including the default settings, may lead to quite
54  * > some latency (i.e. frame buffering) in the encoder. This may cause problems
55  * > with pipeline stalling in non-trivial pipelines, because the encoder latency
56  * > is often considerably higher than the default size of a simple queue
57  * > element. Such problems are caused by one of the queues in the other
58  * > non-x264enc streams/branches filling up and blocking upstream. They can
59  * > be fixed by relaxing the default time/size/buffer limits on the queue
60  * > elements in the non-x264 branches, or using a (single) multiqueue element
61  * > for all branches. Also see the last example below. You can also work around
62  * > this problem by setting the tune=zerolatency property, but this will affect
63  * > overall encoding quality so may not be appropriate for your use case.
64  *
65  * ## Example pipeline
66  * |[
67  * gst-launch-1.0 -v videotestsrc num-buffers=1000 ! x264enc qp-min=18 ! \
68  *   avimux ! filesink location=videotestsrc.avi
69  * ]| This example pipeline will encode a test video source to H264 muxed in an
70  * AVI container, while ensuring a sane minimum quantization factor to avoid
71  * some (excessive) waste. You should ideally never put H264 into an AVI
72  * container (or really anything else, for that matter) - use Matroska or
73  * MP4/QuickTime or MPEG-TS instead.
74  * |[
75  * gst-launch-1.0 -v videotestsrc num-buffers=1000 ! x264enc pass=quant ! \
76  *   matroskamux ! filesink location=videotestsrc.mkv
77  * ]| This example pipeline will encode a test video source to H264 using fixed
78  * quantization, and muxes it in a Matroska container.
79  * |[
80  * gst-launch-1.0 -v videotestsrc num-buffers=1000 ! x264enc pass=5 quantizer=25 speed-preset=6 ! video/x-h264, profile=baseline ! \
81  *   qtmux ! filesink location=videotestsrc.mov
82  * ]| This example pipeline will encode a test video source to H264 using
83  * constant quality at around Q25 using the 'medium' speed/quality preset and
84  * restricting the options used so that the output is H.264 Baseline Profile
85  * compliant and finally multiplexing the output in Quicktime mov format.
86  * |[
87  * gst-launch-1.0 -v videotestsrc num-buffers=1000 ! tee name=t ! queue ! videoconvert ! autovideosink \
88  *   t. ! queue ! x264enc rc-lookahead=5 ! fakesink
89  * ]| This example pipeline will encode a test video source to H.264 while
90  * displaying the input material at the same time.  As mentioned above,
91  * specific settings are needed in this case to avoid pipeline stalling.
92  * Depending on goals and context, other approaches are possible, e.g.
93  * tune=zerolatency might be configured, or queue sizes increased.
94  *
95  */
96
97 #ifdef HAVE_CONFIG_H
98 #  include "config.h"
99 #endif
100
101 #include "gstx264enc.h"
102
103 #include <gst/pbutils/pbutils.h>
104 #include <gst/video/video.h>
105 #include <gst/video/gstvideometa.h>
106 #include <gst/video/gstvideopool.h>
107 #include <gst/base/gstbytereader.h>
108
109 #include <string.h>
110 #include <stdlib.h>
111 #include <gmodule.h>
112
113 GST_DEBUG_CATEGORY_STATIC (x264_enc_debug);
114 #define GST_CAT_DEFAULT x264_enc_debug
115
116 struct _GstX264EncVTable
117 {
118   GModule *module;
119
120 #if X264_BUILD < 153
121   const int *x264_bit_depth;
122 #endif
123   const int *x264_chroma_format;
124   void (*x264_encoder_close) (x264_t *);
125   int (*x264_encoder_delayed_frames) (x264_t *);
126   int (*x264_encoder_encode) (x264_t *, x264_nal_t ** pp_nal, int *pi_nal,
127       x264_picture_t * pic_in, x264_picture_t * pic_out);
128   int (*x264_encoder_headers) (x264_t *, x264_nal_t ** pp_nal, int *pi_nal);
129   void (*x264_encoder_intra_refresh) (x264_t *);
130   int (*x264_encoder_maximum_delayed_frames) (x264_t *);
131   x264_t *(*x264_encoder_open) (x264_param_t *);
132   int (*x264_encoder_reconfig) (x264_t *, x264_param_t *);
133   const x264_level_t (*x264_levels)[];
134   void (*x264_param_apply_fastfirstpass) (x264_param_t *);
135   int (*x264_param_apply_profile) (x264_param_t *, const char *);
136   int (*x264_param_default_preset) (x264_param_t *, const char *preset,
137       const char *tune);
138   int (*x264_param_parse) (x264_param_t *, const char *name, const char *value);
139 };
140
141 static GstX264EncVTable default_vtable;
142
143 static GstX264EncVTable *vtable_8bit = NULL, *vtable_10bit = NULL;
144
145 #if X264_BUILD < 153
146 #define LOAD_SYMBOL(name) G_STMT_START { \
147   if (!g_module_symbol (module, #name, (gpointer *) &vtable->name)) { \
148     GST_ERROR ("Failed to load '" #name "' from '%s'", filename); \
149     goto error; \
150   } \
151 } G_STMT_END;
152
153 #ifdef HAVE_X264_ADDITIONAL_LIBRARIES
154 static GstX264EncVTable *
155 load_x264 (const gchar * filename)
156 {
157   GModule *module;
158   GstX264EncVTable *vtable;
159
160   module = g_module_open (filename, G_MODULE_BIND_LOCAL);
161   if (!module) {
162     GST_ERROR ("Failed to load '%s'", filename);
163     return NULL;
164   }
165
166   vtable = g_new0 (GstX264EncVTable, 1);
167   vtable->module = module;
168
169   if (!g_module_symbol (module, G_STRINGIFY (x264_encoder_open),
170           (gpointer *) & vtable->x264_encoder_open)) {
171     GST_ERROR ("Failed to load '" G_STRINGIFY (x264_encoder_open)
172         "' from '%s'. Incompatible version?", filename);
173     goto error;
174   }
175   LOAD_SYMBOL (x264_bit_depth);
176   LOAD_SYMBOL (x264_chroma_format);
177   LOAD_SYMBOL (x264_encoder_close);
178   LOAD_SYMBOL (x264_encoder_delayed_frames);
179   LOAD_SYMBOL (x264_encoder_encode);
180   LOAD_SYMBOL (x264_encoder_headers);
181   LOAD_SYMBOL (x264_encoder_intra_refresh);
182   LOAD_SYMBOL (x264_encoder_maximum_delayed_frames);
183   LOAD_SYMBOL (x264_encoder_reconfig);
184   LOAD_SYMBOL (x264_levels);
185   LOAD_SYMBOL (x264_param_apply_fastfirstpass);
186   LOAD_SYMBOL (x264_param_apply_profile);
187   LOAD_SYMBOL (x264_param_default_preset);
188   LOAD_SYMBOL (x264_param_parse);
189
190   return vtable;
191
192 error:
193   g_module_close (vtable->module);
194   g_free (vtable);
195   return NULL;
196 }
197
198 static void
199 unload_x264 (GstX264EncVTable * vtable)
200 {
201   if (vtable->module) {
202     g_module_close (vtable->module);
203     g_free (vtable);
204   }
205 }
206 #endif
207
208 #undef LOAD_SYMBOL
209 #endif
210
211 static gboolean
212 gst_x264_enc_add_x264_chroma_format (GstStructure * s,
213     gboolean allow_420_8, gboolean allow_420_10, gboolean allow_422,
214     gboolean allow_444)
215 {
216   GValue fmts = G_VALUE_INIT;
217   GValue fmt = G_VALUE_INIT;
218   gboolean ret = FALSE;
219
220   g_value_init (&fmts, GST_TYPE_LIST);
221   g_value_init (&fmt, G_TYPE_STRING);
222
223   if (vtable_8bit) {
224     gint chroma_format = *vtable_8bit->x264_chroma_format;
225
226     if ((chroma_format == 0 || chroma_format == X264_CSP_I444) && allow_444) {
227       g_value_set_string (&fmt, "Y444");
228       gst_value_list_append_value (&fmts, &fmt);
229     }
230
231     if ((chroma_format == 0 || chroma_format == X264_CSP_I422) && allow_422) {
232       g_value_set_string (&fmt, "Y42B");
233       gst_value_list_append_value (&fmts, &fmt);
234     }
235
236     if ((chroma_format == 0 || chroma_format == X264_CSP_I420) && allow_420_8) {
237       g_value_set_string (&fmt, "I420");
238       gst_value_list_append_value (&fmts, &fmt);
239       g_value_set_string (&fmt, "YV12");
240       gst_value_list_append_value (&fmts, &fmt);
241       g_value_set_string (&fmt, "NV12");
242       gst_value_list_append_value (&fmts, &fmt);
243     }
244   }
245
246   if (vtable_10bit) {
247     gint chroma_format = *vtable_10bit->x264_chroma_format;
248
249     if ((chroma_format == 0 || chroma_format == X264_CSP_I444) && allow_444) {
250       if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
251         g_value_set_string (&fmt, "Y444_10LE");
252       else
253         g_value_set_string (&fmt, "Y444_10BE");
254
255       gst_value_list_append_value (&fmts, &fmt);
256     }
257
258     if ((chroma_format == 0 || chroma_format == X264_CSP_I422) && allow_422) {
259       if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
260         g_value_set_string (&fmt, "I422_10LE");
261       else
262         g_value_set_string (&fmt, "I422_10BE");
263
264       gst_value_list_append_value (&fmts, &fmt);
265     }
266
267     if ((chroma_format == 0 || chroma_format == X264_CSP_I420) && allow_420_10) {
268       if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
269         g_value_set_string (&fmt, "I420_10LE");
270       else
271         g_value_set_string (&fmt, "I420_10BE");
272
273       gst_value_list_append_value (&fmts, &fmt);
274     }
275   }
276
277   if (gst_value_list_get_size (&fmts) != 0) {
278     gst_structure_take_value (s, "format", &fmts);
279     ret = TRUE;
280   } else {
281     g_value_unset (&fmts);
282   }
283
284   g_value_unset (&fmt);
285
286   return ret;
287 }
288
289 #if X264_BUILD < 153
290 static gboolean
291 load_x264_libraries (void)
292 {
293   if (*default_vtable.x264_bit_depth == 8) {
294     vtable_8bit = &default_vtable;
295     GST_INFO ("8-bit depth supported");
296   } else if (*default_vtable.x264_bit_depth == 10) {
297     vtable_10bit = &default_vtable;
298     GST_INFO ("10-bit depth supported");
299   }
300 #ifdef HAVE_X264_ADDITIONAL_LIBRARIES
301   {
302     gchar **libraries = g_strsplit (HAVE_X264_ADDITIONAL_LIBRARIES, ":", -1);
303     gchar **p = libraries;
304
305     while (*p && (!vtable_8bit || !vtable_10bit)) {
306       GstX264EncVTable *vtable = load_x264 (*p);
307
308       if (vtable) {
309         if (!vtable_8bit && *vtable->x264_bit_depth == 8) {
310           GST_INFO ("8-bit depth support loaded from %s", *p);
311           vtable_8bit = vtable;
312         } else if (!vtable_10bit && *vtable->x264_bit_depth == 10) {
313           GST_INFO ("10-bit depth support loaded from %s", *p);
314           vtable_10bit = vtable;
315         } else {
316           unload_x264 (vtable);
317         }
318       }
319
320       p++;
321     }
322     g_strfreev (libraries);
323   }
324 #endif
325
326   if (!vtable_8bit && !vtable_10bit)
327     return FALSE;
328
329   return TRUE;
330 }
331
332 #else /* X264_BUILD >= 153 */
333
334 static gboolean
335 load_x264_libraries (void)
336 {
337 #if X264_BIT_DEPTH == 0         /* all */
338   GST_INFO ("8-bit depth and 10-bit depth supported");
339   vtable_8bit = &default_vtable;
340   vtable_10bit = &default_vtable;
341 #elif X264_BIT_DEPTH == 8
342   GST_INFO ("Only 8-bit depth supported");
343   vtable_8bit = &default_vtable;
344 #elif X264_BIT_DEPTH == 10
345   GST_INFO ("Only 10-bit depth supported");
346   vtable_10bit = &default_vtable;
347 #else
348 #error "unexpected X264_BIT_DEPTH value"
349 #endif
350
351 #ifdef HAVE_X264_ADDITIONAL_LIBRARIES
352   GST_WARNING ("Ignoring configured additional libraries %s, using libx264 "
353       "version enabled for multiple bit depths",
354       HAVE_X264_ADDITIONAL_LIBRARIES);
355 #endif
356
357   return TRUE;
358 }
359
360 #endif
361
362 enum
363 {
364   ARG_0,
365   ARG_THREADS,
366   ARG_SLICED_THREADS,
367   ARG_SYNC_LOOKAHEAD,
368   ARG_PASS,
369   ARG_QUANTIZER,
370   ARG_MULTIPASS_CACHE_FILE,
371   ARG_BYTE_STREAM,
372   ARG_BITRATE,
373   ARG_INTRA_REFRESH,
374   ARG_VBV_BUF_CAPACITY,
375   ARG_ME,
376   ARG_SUBME,
377   ARG_ANALYSE,
378   ARG_DCT8x8,
379   ARG_REF,
380   ARG_BFRAMES,
381   ARG_B_ADAPT,
382   ARG_B_PYRAMID,
383   ARG_WEIGHTB,
384   ARG_SPS_ID,
385   ARG_AU_NALU,
386   ARG_TRELLIS,
387   ARG_KEYINT_MAX,
388   ARG_CABAC,
389   ARG_QP_MIN,
390   ARG_QP_MAX,
391   ARG_QP_STEP,
392   ARG_IP_FACTOR,
393   ARG_PB_FACTOR,
394   ARG_RC_MB_TREE,
395   ARG_RC_LOOKAHEAD,
396   ARG_NR,
397   ARG_INTERLACED,
398   ARG_OPTION_STRING,
399   ARG_SPEED_PRESET,
400   ARG_PSY_TUNE,
401   ARG_TUNE,
402   ARG_FRAME_PACKING,
403   ARG_INSERT_VUI,
404 };
405
406 #define ARG_THREADS_DEFAULT            0        /* 0 means 'auto' which is 1.5x number of CPU cores */
407 #define ARG_PASS_DEFAULT               0
408 #define ARG_QUANTIZER_DEFAULT          21
409 #define ARG_MULTIPASS_CACHE_FILE_DEFAULT "x264.log"
410 #define ARG_BYTE_STREAM_DEFAULT        FALSE
411 #define ARG_BITRATE_DEFAULT            (2 * 1024)
412 #define ARG_VBV_BUF_CAPACITY_DEFAULT   600
413 #define ARG_ME_DEFAULT                 X264_ME_HEX
414 #define ARG_SUBME_DEFAULT              1
415 #define ARG_ANALYSE_DEFAULT            0
416 #define ARG_DCT8x8_DEFAULT             FALSE
417 #define ARG_REF_DEFAULT                3
418 #define ARG_BFRAMES_DEFAULT            0
419 #define ARG_B_ADAPT_DEFAULT            TRUE
420 #define ARG_B_PYRAMID_DEFAULT          FALSE
421 #define ARG_WEIGHTB_DEFAULT            FALSE
422 #define ARG_SPS_ID_DEFAULT             0
423 #define ARG_AU_NALU_DEFAULT            TRUE
424 #define ARG_TRELLIS_DEFAULT            TRUE
425 #define ARG_KEYINT_MAX_DEFAULT         0
426 #define ARG_CABAC_DEFAULT              TRUE
427 #define ARG_QP_MIN_DEFAULT             10
428 #define ARG_QP_MAX_DEFAULT             51
429 #define ARG_QP_STEP_DEFAULT            4
430 #define ARG_IP_FACTOR_DEFAULT          1.4
431 #define ARG_PB_FACTOR_DEFAULT          1.3
432 #define ARG_NR_DEFAULT                 0
433 #define ARG_INTERLACED_DEFAULT         FALSE
434 #define ARG_SLICED_THREADS_DEFAULT     FALSE
435 #define ARG_SYNC_LOOKAHEAD_DEFAULT     -1
436 #define ARG_RC_MB_TREE_DEFAULT         TRUE
437 #define ARG_RC_LOOKAHEAD_DEFAULT       40
438 #define ARG_INTRA_REFRESH_DEFAULT      FALSE
439 #define ARG_OPTION_STRING_DEFAULT      ""
440 static GString *x264enc_defaults;
441 #define ARG_SPEED_PRESET_DEFAULT       6        /* 'medium' preset - matches x264 CLI default */
442 #define ARG_PSY_TUNE_DEFAULT           0        /* no psy tuning */
443 #define ARG_TUNE_DEFAULT               0        /* no tuning */
444 #define ARG_FRAME_PACKING_DEFAULT      -1       /* automatic (none, or from input caps) */
445 #define ARG_INSERT_VUI_DEFAULT         TRUE
446
447 enum
448 {
449   GST_X264_ENC_STREAM_FORMAT_FROM_PROPERTY,
450   GST_X264_ENC_STREAM_FORMAT_AVC,
451   GST_X264_ENC_STREAM_FORMAT_BYTE_STREAM
452 };
453
454 enum
455 {
456   GST_X264_ENC_PASS_CBR = 0,
457   GST_X264_ENC_PASS_QUANT = 0x04,
458   GST_X264_ENC_PASS_QUAL,
459   GST_X264_ENC_PASS_PASS1 = 0x11,
460   GST_X264_ENC_PASS_PASS2,
461   GST_X264_ENC_PASS_PASS3
462 };
463
464 #define GST_X264_ENC_PASS_TYPE (gst_x264_enc_pass_get_type())
465 static GType
466 gst_x264_enc_pass_get_type (void)
467 {
468   static GType pass_type = 0;
469
470   static const GEnumValue pass_types[] = {
471     {GST_X264_ENC_PASS_CBR, "Constant Bitrate Encoding", "cbr"},
472     {GST_X264_ENC_PASS_QUANT, "Constant Quantizer", "quant"},
473     {GST_X264_ENC_PASS_QUAL, "Constant Quality", "qual"},
474     {GST_X264_ENC_PASS_PASS1, "VBR Encoding - Pass 1", "pass1"},
475     {GST_X264_ENC_PASS_PASS2, "VBR Encoding - Pass 2", "pass2"},
476     {GST_X264_ENC_PASS_PASS3, "VBR Encoding - Pass 3", "pass3"},
477     {0, NULL, NULL}
478   };
479
480   if (!pass_type) {
481     pass_type = g_enum_register_static ("GstX264EncPass", pass_types);
482   }
483   return pass_type;
484 }
485
486 #define GST_X264_ENC_ME_TYPE (gst_x264_enc_me_get_type())
487 static GType
488 gst_x264_enc_me_get_type (void)
489 {
490   static GType me_type = 0;
491   static GEnumValue *me_types;
492   int n, i;
493
494   if (me_type != 0)
495     return me_type;
496
497   n = 0;
498   while (x264_motion_est_names[n] != NULL)
499     n++;
500
501   me_types = g_new0 (GEnumValue, n + 1);
502
503   for (i = 0; i < n; i++) {
504     me_types[i].value = i;
505     me_types[i].value_name = x264_motion_est_names[i];
506     me_types[i].value_nick = x264_motion_est_names[i];
507   }
508
509   me_type = g_enum_register_static ("GstX264EncMe", me_types);
510
511   return me_type;
512 }
513
514 #define GST_X264_ENC_ANALYSE_TYPE (gst_x264_enc_analyse_get_type())
515 static GType
516 gst_x264_enc_analyse_get_type (void)
517 {
518   static GType analyse_type = 0;
519   static const GFlagsValue analyse_types[] = {
520     {X264_ANALYSE_I4x4, "i4x4", "i4x4"},
521     {X264_ANALYSE_I8x8, "i8x8", "i8x8"},
522     {X264_ANALYSE_PSUB16x16, "p8x8", "p8x8"},
523     {X264_ANALYSE_PSUB8x8, "p4x4", "p4x4"},
524     {X264_ANALYSE_BSUB16x16, "b8x8", "b8x8"},
525     {0, NULL, NULL},
526   };
527
528   if (!analyse_type) {
529     analyse_type = g_flags_register_static ("GstX264EncAnalyse", analyse_types);
530   }
531   return analyse_type;
532 }
533
534 #define GST_X264_ENC_SPEED_PRESET_TYPE (gst_x264_enc_speed_preset_get_type())
535 static GType
536 gst_x264_enc_speed_preset_get_type (void)
537 {
538   static GType speed_preset_type = 0;
539   static GEnumValue *speed_preset_types;
540   int n, i;
541
542   if (speed_preset_type != 0)
543     return speed_preset_type;
544
545   n = 0;
546   while (x264_preset_names[n] != NULL)
547     n++;
548
549   speed_preset_types = g_new0 (GEnumValue, n + 2);
550
551   speed_preset_types[0].value = 0;
552   speed_preset_types[0].value_name = "No preset";
553   speed_preset_types[0].value_nick = "None";
554
555   for (i = 1; i <= n; i++) {
556     speed_preset_types[i].value = i;
557     speed_preset_types[i].value_name = x264_preset_names[i - 1];
558     speed_preset_types[i].value_nick = x264_preset_names[i - 1];
559   }
560
561   speed_preset_type =
562       g_enum_register_static ("GstX264EncPreset", speed_preset_types);
563
564   return speed_preset_type;
565 }
566
567 static const GFlagsValue tune_types[] = {
568   {0x0, "No tuning", "none"},
569   {0x1, "Still image", "stillimage"},
570   {0x2, "Fast decode", "fastdecode"},
571   {0x4, "Zero latency", "zerolatency"},
572   {0, NULL, NULL},
573 };
574
575 #define GST_X264_ENC_TUNE_TYPE (gst_x264_enc_tune_get_type())
576 static GType
577 gst_x264_enc_tune_get_type (void)
578 {
579   static GType tune_type = 0;
580
581   if (!tune_type) {
582     tune_type = g_flags_register_static ("GstX264EncTune", tune_types + 1);
583   }
584   return tune_type;
585 }
586
587 enum
588 {
589   GST_X264_ENC_TUNE_NONE,
590   GST_X264_ENC_TUNE_FILM,
591   GST_X264_ENC_TUNE_ANIMATION,
592   GST_X264_ENC_TUNE_GRAIN,
593   GST_X264_ENC_TUNE_PSNR,
594   GST_X264_ENC_TUNE_SSIM,
595   GST_X264_ENC_TUNE_LAST
596 };
597
598 static const GEnumValue psy_tune_types[] = {
599   {GST_X264_ENC_TUNE_NONE, "No tuning", "none"},
600   {GST_X264_ENC_TUNE_FILM, "Film", "film"},
601   {GST_X264_ENC_TUNE_ANIMATION, "Animation", "animation"},
602   {GST_X264_ENC_TUNE_GRAIN, "Grain", "grain"},
603   {GST_X264_ENC_TUNE_PSNR, "PSNR", "psnr"},
604   {GST_X264_ENC_TUNE_SSIM, "SSIM", "ssim"},
605   {0, NULL, NULL},
606 };
607
608 #define GST_X264_ENC_PSY_TUNE_TYPE (gst_x264_enc_psy_tune_get_type())
609 static GType
610 gst_x264_enc_psy_tune_get_type (void)
611 {
612   static GType psy_tune_type = 0;
613
614   if (!psy_tune_type) {
615     psy_tune_type =
616         g_enum_register_static ("GstX264EncPsyTune", psy_tune_types);
617   }
618   return psy_tune_type;
619 }
620
621 static void
622 gst_x264_enc_build_tunings_string (GstX264Enc * x264enc)
623 {
624   int i = 1;
625
626   if (x264enc->tunings)
627     g_string_free (x264enc->tunings, TRUE);
628
629   if (x264enc->psy_tune) {
630     x264enc->tunings =
631         g_string_new (psy_tune_types[x264enc->psy_tune].value_nick);
632   } else {
633     x264enc->tunings = g_string_new (NULL);
634   }
635
636   while (tune_types[i].value_name) {
637     if (x264enc->tune & (1 << (i - 1)))
638       g_string_append_printf (x264enc->tunings, "%s%s",
639           x264enc->tunings->len ? "," : "", tune_types[i].value_nick);
640     i++;
641   }
642
643   if (x264enc->tunings->len)
644     GST_DEBUG_OBJECT (x264enc, "Constructed tunings string: %s",
645         x264enc->tunings->str);
646 }
647
648 #define GST_X264_ENC_FRAME_PACKING_TYPE (gst_x264_enc_frame_packing_get_type())
649 static GType
650 gst_x264_enc_frame_packing_get_type (void)
651 {
652   static GType fpa_type = 0;
653
654   static const GEnumValue fpa_types[] = {
655     {-1, "Automatic (use incoming video information)", "auto"},
656     {0, "checkerboard - Left and Right pixels alternate in a checkerboard pattern", "checkerboard"},
657     {1, "column interleaved - Alternating pixel columns represent Left and Right views", "column-interleaved"},
658     {2, "row interleaved - Alternating pixel rows represent Left and Right views", "row-interleaved"},
659     {3, "side by side - The left half of the frame contains the Left eye view, the right half the Right eye view", "side-by-side"},
660     {4, "top bottom - L is on top, R on bottom", "top-bottom"},
661     {5, "frame interleaved - Each frame contains either Left or Right view alternately", "frame-interleaved"},
662     {0, NULL, NULL}
663   };
664
665   if (!fpa_type) {
666     fpa_type = g_enum_register_static ("GstX264EncFramePacking", fpa_types);
667   }
668   return fpa_type;
669 }
670
671 static gint
672 gst_x264_enc_mview_mode_to_frame_packing (GstVideoMultiviewMode mode)
673 {
674   switch (mode) {
675     case GST_VIDEO_MULTIVIEW_MODE_CHECKERBOARD:
676       return 0;
677     case GST_VIDEO_MULTIVIEW_MODE_COLUMN_INTERLEAVED:
678       return 1;
679     case GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED:
680       return 2;
681     case GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE:
682       return 3;
683     case GST_VIDEO_MULTIVIEW_MODE_TOP_BOTTOM:
684       return 4;
685     case GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME:
686       return 5;
687     default:
688       break;
689   }
690
691   return -1;
692 }
693
694 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
695     GST_PAD_SRC,
696     GST_PAD_ALWAYS,
697     GST_STATIC_CAPS ("video/x-h264, "
698         "framerate = (fraction) [0/1, MAX], "
699         "width = (int) [ 1, MAX ], " "height = (int) [ 1, MAX ], "
700         "stream-format = (string) { avc, byte-stream }, "
701         "alignment = (string) au, "
702         "profile = (string) { high-4:4:4, high-4:2:2, high-10, high, main,"
703         " baseline, constrained-baseline, high-4:4:4-intra, high-4:2:2-intra,"
704         " high-10-intra }")
705     );
706
707 static void gst_x264_enc_finalize (GObject * object);
708 static gboolean gst_x264_enc_start (GstVideoEncoder * encoder);
709 static gboolean gst_x264_enc_stop (GstVideoEncoder * encoder);
710 static gboolean gst_x264_enc_flush (GstVideoEncoder * encoder);
711
712 static gboolean gst_x264_enc_init_encoder (GstX264Enc * encoder);
713 static void gst_x264_enc_close_encoder (GstX264Enc * encoder);
714
715 static GstFlowReturn gst_x264_enc_finish (GstVideoEncoder * encoder);
716 static GstFlowReturn gst_x264_enc_handle_frame (GstVideoEncoder * encoder,
717     GstVideoCodecFrame * frame);
718 static void gst_x264_enc_flush_frames (GstX264Enc * encoder, gboolean send);
719 static GstFlowReturn gst_x264_enc_encode_frame (GstX264Enc * encoder,
720     x264_picture_t * pic_in, GstVideoCodecFrame * input_frame, int *i_nal,
721     gboolean send);
722 static gboolean gst_x264_enc_set_format (GstVideoEncoder * video_enc,
723     GstVideoCodecState * state);
724 static gboolean gst_x264_enc_propose_allocation (GstVideoEncoder * encoder,
725     GstQuery * query);
726
727 static void gst_x264_enc_set_property (GObject * object, guint prop_id,
728     const GValue * value, GParamSpec * pspec);
729 static void gst_x264_enc_get_property (GObject * object, guint prop_id,
730     GValue * value, GParamSpec * pspec);
731 static gboolean x264_element_init (GstPlugin * plugin);
732
733 typedef gboolean (*LoadPresetFunc) (GstPreset * preset, const gchar * name);
734
735 LoadPresetFunc parent_load_preset = NULL;
736
737 static gboolean
738 gst_x264_enc_load_preset (GstPreset * preset, const gchar * name)
739 {
740   GstX264Enc *enc = GST_X264_ENC (preset);
741   gboolean res;
742
743   gst_encoder_bitrate_profile_manager_start_loading_preset
744       (enc->bitrate_manager);
745   res = parent_load_preset (preset, name);
746   gst_encoder_bitrate_profile_manager_end_loading_preset (enc->bitrate_manager,
747       res ? name : NULL);
748
749   return res;
750 }
751
752 static void
753 gst_x264_enc_preset_interface_init (GstPresetInterface * iface)
754 {
755   parent_load_preset = iface->load_preset;
756   iface->load_preset = gst_x264_enc_load_preset;
757 }
758
759 #define gst_x264_enc_parent_class parent_class
760 G_DEFINE_TYPE_WITH_CODE (GstX264Enc, gst_x264_enc, GST_TYPE_VIDEO_ENCODER,
761     G_IMPLEMENT_INTERFACE (GST_TYPE_PRESET,
762         gst_x264_enc_preset_interface_init));
763 GST_ELEMENT_REGISTER_DEFINE_CUSTOM (x264enc, x264_element_init)
764 /* don't forget to free the string after use */
765      static const gchar *gst_x264_enc_build_partitions (gint analyse)
766 {
767   GString *string;
768
769   if (!analyse)
770     return NULL;
771
772   string = g_string_new (NULL);
773   if (analyse & X264_ANALYSE_I4x4)
774     g_string_append (string, "i4x4");
775   if (analyse & X264_ANALYSE_I8x8)
776     g_string_append (string, ",i8x8");
777   if (analyse & X264_ANALYSE_PSUB16x16)
778     g_string_append (string, ",p8x8");
779   if (analyse & X264_ANALYSE_PSUB8x8)
780     g_string_append (string, ",p4x4");
781   if (analyse & X264_ANALYSE_BSUB16x16)
782     g_string_append (string, ",b8x8");
783
784   return (const gchar *) g_string_free (string, FALSE);
785 }
786
787 static void
788 check_formats (const gchar * str, gboolean * has_420_8, gboolean * has_420_10,
789     gboolean * has_422, gboolean * has_444)
790 {
791   if (g_str_has_prefix (str, "high-4:4:4"))
792     *has_444 = TRUE;
793   else if (g_str_has_prefix (str, "high-4:2:2"))
794     *has_422 = TRUE;
795   else if (g_str_has_prefix (str, "high-10"))
796     *has_420_10 = TRUE;
797   else
798     *has_420_8 = TRUE;
799 }
800
801
802 /* allowed input caps depending on whether libx264 was built for 8 or 10 bits */
803 static GstCaps *
804 gst_x264_enc_sink_getcaps (GstVideoEncoder * enc, GstCaps * filter)
805 {
806   GstCaps *supported_incaps;
807   GstCaps *allowed;
808   GstCaps *filter_caps, *fcaps;
809   gint i, j, k;
810
811   supported_incaps =
812       gst_pad_get_pad_template_caps (GST_VIDEO_ENCODER_SINK_PAD (enc));
813
814   /* Allow downstream to specify width/height/framerate/PAR constraints
815    * and forward them upstream for video converters to handle
816    */
817   allowed = gst_pad_get_allowed_caps (enc->srcpad);
818
819   if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) {
820     fcaps = supported_incaps;
821     goto done;
822   }
823
824   GST_LOG_OBJECT (enc, "template caps %" GST_PTR_FORMAT, supported_incaps);
825   GST_LOG_OBJECT (enc, "allowed caps %" GST_PTR_FORMAT, allowed);
826
827   filter_caps = gst_caps_new_empty ();
828
829   for (i = 0; i < gst_caps_get_size (supported_incaps); i++) {
830     GQuark q_name =
831         gst_structure_get_name_id (gst_caps_get_structure (supported_incaps,
832             i));
833
834     for (j = 0; j < gst_caps_get_size (allowed); j++) {
835       const GstStructure *allowed_s = gst_caps_get_structure (allowed, j);
836       const GValue *val;
837       GstStructure *s;
838
839       /* FIXME Find a way to reuse gst_video_encoder_proxy_getcaps so that
840        * we do not need to copy that logic */
841       s = gst_structure_new_id_empty (q_name);
842       if ((val = gst_structure_get_value (allowed_s, "width")))
843         gst_structure_set_value (s, "width", val);
844       if ((val = gst_structure_get_value (allowed_s, "height")))
845         gst_structure_set_value (s, "height", val);
846       if ((val = gst_structure_get_value (allowed_s, "framerate")))
847         gst_structure_set_value (s, "framerate", val);
848       if ((val = gst_structure_get_value (allowed_s, "pixel-aspect-ratio")))
849         gst_structure_set_value (s, "pixel-aspect-ratio", val);
850       if ((val = gst_structure_get_value (allowed_s, "colorimetry")))
851         gst_structure_set_value (s, "colorimetry", val);
852       if ((val = gst_structure_get_value (allowed_s, "chroma-site")))
853         gst_structure_set_value (s, "chroma-site", val);
854
855       if ((val = gst_structure_get_value (allowed_s, "profile"))) {
856         gboolean has_420_8 = FALSE;
857         gboolean has_420_10 = FALSE;
858         gboolean has_422 = FALSE;
859         gboolean has_444 = FALSE;
860
861         if (G_VALUE_HOLDS_STRING (val)) {
862           check_formats (g_value_get_string (val), &has_420_8, &has_420_10,
863               &has_422, &has_444);
864         } else if (GST_VALUE_HOLDS_LIST (val)) {
865           for (k = 0; k < gst_value_list_get_size (val); k++) {
866             const GValue *vlist = gst_value_list_get_value (val, k);
867
868             if (G_VALUE_HOLDS_STRING (vlist))
869               check_formats (g_value_get_string (vlist), &has_420_8,
870                   &has_420_10, &has_422, &has_444);
871           }
872         }
873
874         gst_x264_enc_add_x264_chroma_format (s, has_420_8, has_420_10, has_422,
875             has_444);
876       }
877
878       filter_caps = gst_caps_merge_structure (filter_caps, s);
879     }
880   }
881
882   fcaps = gst_caps_intersect (filter_caps, supported_incaps);
883   gst_caps_unref (filter_caps);
884   gst_caps_unref (supported_incaps);
885
886   if (filter) {
887     GST_LOG_OBJECT (enc, "intersecting with %" GST_PTR_FORMAT, filter);
888     filter_caps = gst_caps_intersect (fcaps, filter);
889     gst_caps_unref (fcaps);
890     fcaps = filter_caps;
891   }
892
893 done:
894   gst_caps_replace (&allowed, NULL);
895
896   GST_LOG_OBJECT (enc, "proxy caps %" GST_PTR_FORMAT, fcaps);
897
898   return fcaps;
899 }
900
901 static gboolean
902 gst_x264_enc_sink_query (GstVideoEncoder * enc, GstQuery * query)
903 {
904   GstPad *pad = GST_VIDEO_ENCODER_SINK_PAD (enc);
905   gboolean ret = FALSE;
906
907   GST_DEBUG ("Received %s query on sinkpad, %" GST_PTR_FORMAT,
908       GST_QUERY_TYPE_NAME (query), query);
909
910   switch (GST_QUERY_TYPE (query)) {
911     case GST_QUERY_ACCEPT_CAPS:{
912       GstCaps *acceptable, *caps;
913
914       acceptable = gst_pad_get_pad_template_caps (pad);
915
916       gst_query_parse_accept_caps (query, &caps);
917
918       gst_query_set_accept_caps_result (query,
919           gst_caps_is_subset (caps, acceptable));
920       gst_caps_unref (acceptable);
921       ret = TRUE;
922     }
923       break;
924     default:
925       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_query (enc, query);
926       break;
927   }
928
929   return ret;
930 }
931
932 static void
933 gst_x264_enc_class_init (GstX264EncClass * klass)
934 {
935   GObjectClass *gobject_class;
936   GstElementClass *element_class;
937   GstVideoEncoderClass *gstencoder_class;
938   const gchar *partitions = NULL;
939   GstPadTemplate *sink_templ;
940   GstCaps *supported_sinkcaps;
941
942   x264enc_defaults = g_string_new ("");
943
944   gobject_class = G_OBJECT_CLASS (klass);
945   element_class = GST_ELEMENT_CLASS (klass);
946   gstencoder_class = GST_VIDEO_ENCODER_CLASS (klass);
947
948   gobject_class->set_property = gst_x264_enc_set_property;
949   gobject_class->get_property = gst_x264_enc_get_property;
950   gobject_class->finalize = gst_x264_enc_finalize;
951
952   gstencoder_class->set_format = GST_DEBUG_FUNCPTR (gst_x264_enc_set_format);
953   gstencoder_class->handle_frame =
954       GST_DEBUG_FUNCPTR (gst_x264_enc_handle_frame);
955   gstencoder_class->start = GST_DEBUG_FUNCPTR (gst_x264_enc_start);
956   gstencoder_class->stop = GST_DEBUG_FUNCPTR (gst_x264_enc_stop);
957   gstencoder_class->flush = GST_DEBUG_FUNCPTR (gst_x264_enc_flush);
958   gstencoder_class->finish = GST_DEBUG_FUNCPTR (gst_x264_enc_finish);
959   gstencoder_class->getcaps = GST_DEBUG_FUNCPTR (gst_x264_enc_sink_getcaps);
960   gstencoder_class->propose_allocation =
961       GST_DEBUG_FUNCPTR (gst_x264_enc_propose_allocation);
962   gstencoder_class->sink_query = GST_DEBUG_FUNCPTR (gst_x264_enc_sink_query);
963
964   /* options for which we don't use string equivalents */
965   g_object_class_install_property (gobject_class, ARG_PASS,
966       g_param_spec_enum ("pass", "Encoding pass/type",
967           "Encoding pass/type", GST_X264_ENC_PASS_TYPE,
968           ARG_PASS_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
969   g_object_class_install_property (gobject_class, ARG_QUANTIZER,
970       g_param_spec_uint ("quantizer", "Constant Quantizer",
971           "Constant quantizer or quality to apply",
972           0, 50, ARG_QUANTIZER_DEFAULT,
973           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
974   g_object_class_install_property (gobject_class, ARG_BITRATE,
975       g_param_spec_uint ("bitrate", "Bitrate", "Bitrate in kbit/sec", 1,
976           2000 * 1024, ARG_BITRATE_DEFAULT,
977           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
978           GST_PARAM_MUTABLE_PLAYING));
979   g_object_class_install_property (gobject_class, ARG_VBV_BUF_CAPACITY,
980       g_param_spec_uint ("vbv-buf-capacity", "VBV buffer capacity",
981           "Size of the VBV buffer in milliseconds",
982           0, 10000, ARG_VBV_BUF_CAPACITY_DEFAULT,
983           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
984           GST_PARAM_MUTABLE_PLAYING));
985   g_object_class_install_property (gobject_class, ARG_SPEED_PRESET,
986       g_param_spec_enum ("speed-preset", "Speed/quality preset",
987           "Preset name for speed/quality tradeoff options (can affect decode "
988           "compatibility - impose restrictions separately for your target decoder)",
989           GST_X264_ENC_SPEED_PRESET_TYPE, ARG_SPEED_PRESET_DEFAULT,
990           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
991   g_object_class_install_property (gobject_class, ARG_PSY_TUNE,
992       g_param_spec_enum ("psy-tune", "Psychovisual tuning preset",
993           "Preset name for psychovisual tuning options",
994           GST_X264_ENC_PSY_TUNE_TYPE, ARG_PSY_TUNE_DEFAULT,
995           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
996   g_object_class_install_property (gobject_class, ARG_TUNE,
997       g_param_spec_flags ("tune", "Content tuning preset",
998           "Preset name for non-psychovisual tuning options",
999           GST_X264_ENC_TUNE_TYPE, ARG_TUNE_DEFAULT,
1000           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1001   g_object_class_install_property (gobject_class, ARG_OPTION_STRING,
1002       g_param_spec_string ("option-string", "Option string",
1003           "String of x264 options (overridden by element properties)"
1004           " in the format \"key1=value1:key2=value2\".",
1005           ARG_OPTION_STRING_DEFAULT,
1006           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1007
1008   g_object_class_install_property (gobject_class, ARG_FRAME_PACKING,
1009       g_param_spec_enum ("frame-packing", "Frame Packing",
1010           "Set frame packing mode for Stereoscopic content",
1011           GST_X264_ENC_FRAME_PACKING_TYPE, ARG_FRAME_PACKING_DEFAULT,
1012           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1013
1014   g_object_class_install_property (gobject_class, ARG_INSERT_VUI,
1015       g_param_spec_boolean ("insert-vui", "Insert VUI",
1016           "Insert VUI NAL in stream",
1017           ARG_INSERT_VUI_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1018
1019   /* options for which we _do_ use string equivalents */
1020   g_object_class_install_property (gobject_class, ARG_THREADS,
1021       g_param_spec_uint ("threads", "Threads",
1022           "Number of threads used by the codec (0 for automatic)",
1023           0, G_MAXINT, ARG_THREADS_DEFAULT,
1024           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1025   /* NOTE: this first string append doesn't require the ':' delimiter but the
1026    * rest do */
1027   g_string_append_printf (x264enc_defaults, "threads=%d", ARG_THREADS_DEFAULT);
1028   g_object_class_install_property (gobject_class, ARG_SLICED_THREADS,
1029       g_param_spec_boolean ("sliced-threads", "Sliced Threads",
1030           "Low latency but lower efficiency threading",
1031           ARG_SLICED_THREADS_DEFAULT,
1032           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1033   g_string_append_printf (x264enc_defaults, ":sliced-threads=%d",
1034       ARG_SLICED_THREADS_DEFAULT);
1035   g_object_class_install_property (gobject_class, ARG_SYNC_LOOKAHEAD,
1036       g_param_spec_int ("sync-lookahead", "Sync Lookahead",
1037           "Number of buffer frames for threaded lookahead (-1 for automatic)",
1038           -1, 250, ARG_SYNC_LOOKAHEAD_DEFAULT,
1039           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1040   g_string_append_printf (x264enc_defaults, ":sync-lookahead=%d",
1041       ARG_SYNC_LOOKAHEAD_DEFAULT);
1042   g_object_class_install_property (gobject_class, ARG_MULTIPASS_CACHE_FILE,
1043       g_param_spec_string ("multipass-cache-file", "Multipass Cache File",
1044           "Filename for multipass cache file",
1045           ARG_MULTIPASS_CACHE_FILE_DEFAULT,
1046           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1047   g_string_append_printf (x264enc_defaults, ":stats=%s",
1048       ARG_MULTIPASS_CACHE_FILE_DEFAULT);
1049   g_object_class_install_property (gobject_class, ARG_BYTE_STREAM,
1050       g_param_spec_boolean ("byte-stream", "Byte Stream",
1051           "Generate byte stream format of NALU", ARG_BYTE_STREAM_DEFAULT,
1052           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1053   g_string_append_printf (x264enc_defaults, ":annexb=%d",
1054       ARG_BYTE_STREAM_DEFAULT);
1055   g_object_class_install_property (gobject_class, ARG_INTRA_REFRESH,
1056       g_param_spec_boolean ("intra-refresh", "Intra Refresh",
1057           "Use Periodic Intra Refresh instead of IDR frames",
1058           ARG_INTRA_REFRESH_DEFAULT,
1059           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1060   g_string_append_printf (x264enc_defaults, ":intra-refresh=%d",
1061       ARG_INTRA_REFRESH_DEFAULT);
1062   g_object_class_install_property (gobject_class, ARG_ME,
1063       g_param_spec_enum ("me", "Motion Estimation",
1064           "Integer pixel motion estimation method", GST_X264_ENC_ME_TYPE,
1065           ARG_ME_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1066   g_string_append_printf (x264enc_defaults, ":me=%s",
1067       x264_motion_est_names[ARG_ME_DEFAULT]);
1068   g_object_class_install_property (gobject_class, ARG_SUBME,
1069       g_param_spec_uint ("subme", "Subpixel Motion Estimation",
1070           "Subpixel motion estimation and partition decision quality: 1=fast, 10=best",
1071           1, 10, ARG_SUBME_DEFAULT,
1072           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1073   g_string_append_printf (x264enc_defaults, ":subme=%d", ARG_SUBME_DEFAULT);
1074   g_object_class_install_property (gobject_class, ARG_ANALYSE,
1075       g_param_spec_flags ("analyse", "Analyse", "Partitions to consider",
1076           GST_X264_ENC_ANALYSE_TYPE, ARG_ANALYSE_DEFAULT,
1077           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1078   partitions = gst_x264_enc_build_partitions (ARG_ANALYSE_DEFAULT);
1079   if (partitions) {
1080     g_string_append_printf (x264enc_defaults, ":partitions=%s", partitions);
1081     g_free ((gpointer) partitions);
1082   }
1083   g_object_class_install_property (gobject_class, ARG_DCT8x8,
1084       g_param_spec_boolean ("dct8x8", "DCT8x8",
1085           "Adaptive spatial transform size", ARG_DCT8x8_DEFAULT,
1086           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1087   g_string_append_printf (x264enc_defaults, ":8x8dct=%d", ARG_DCT8x8_DEFAULT);
1088   g_object_class_install_property (gobject_class, ARG_REF,
1089       g_param_spec_uint ("ref", "Reference Frames",
1090           "Number of reference frames",
1091           1, 16, ARG_REF_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1092   g_string_append_printf (x264enc_defaults, ":ref=%d", ARG_REF_DEFAULT);
1093   g_object_class_install_property (gobject_class, ARG_BFRAMES,
1094       g_param_spec_uint ("bframes", "B-Frames",
1095           "Number of B-frames between I and P",
1096           0, 16, ARG_BFRAMES_DEFAULT,
1097           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1098   g_string_append_printf (x264enc_defaults, ":bframes=%d", ARG_BFRAMES_DEFAULT);
1099   g_object_class_install_property (gobject_class, ARG_B_ADAPT,
1100       g_param_spec_boolean ("b-adapt", "B-Adapt",
1101           "Automatically decide how many B-frames to use",
1102           ARG_B_ADAPT_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1103   g_string_append_printf (x264enc_defaults, ":b-adapt=%d", ARG_B_ADAPT_DEFAULT);
1104   g_object_class_install_property (gobject_class, ARG_B_PYRAMID,
1105       g_param_spec_boolean ("b-pyramid", "B-Pyramid",
1106           "Keep some B-frames as references", ARG_B_PYRAMID_DEFAULT,
1107           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1108   g_string_append_printf (x264enc_defaults, ":b-pyramid=%s",
1109       x264_b_pyramid_names[ARG_B_PYRAMID_DEFAULT]);
1110   g_object_class_install_property (gobject_class, ARG_WEIGHTB,
1111       g_param_spec_boolean ("weightb", "Weighted B-Frames",
1112           "Weighted prediction for B-frames", ARG_WEIGHTB_DEFAULT,
1113           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1114   g_string_append_printf (x264enc_defaults, ":weightb=%d", ARG_WEIGHTB_DEFAULT);
1115   g_object_class_install_property (gobject_class, ARG_SPS_ID,
1116       g_param_spec_uint ("sps-id", "SPS ID",
1117           "SPS and PPS ID number",
1118           0, 31, ARG_SPS_ID_DEFAULT,
1119           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1120   g_string_append_printf (x264enc_defaults, ":sps-id=%d", ARG_SPS_ID_DEFAULT);
1121   g_object_class_install_property (gobject_class, ARG_AU_NALU,
1122       g_param_spec_boolean ("aud", "AUD",
1123           "Use AU (Access Unit) delimiter", ARG_AU_NALU_DEFAULT,
1124           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1125   g_string_append_printf (x264enc_defaults, ":aud=%d", ARG_AU_NALU_DEFAULT);
1126   g_object_class_install_property (gobject_class, ARG_TRELLIS,
1127       g_param_spec_boolean ("trellis", "Trellis quantization",
1128           "Enable trellis searched quantization", ARG_TRELLIS_DEFAULT,
1129           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1130   g_string_append_printf (x264enc_defaults, ":trellis=%d", ARG_TRELLIS_DEFAULT);
1131   g_object_class_install_property (gobject_class, ARG_KEYINT_MAX,
1132       g_param_spec_uint ("key-int-max", "Key-frame maximal interval",
1133           "Maximal distance between two key-frames (0 for automatic)",
1134           0, G_MAXINT, ARG_KEYINT_MAX_DEFAULT,
1135           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1136   g_string_append_printf (x264enc_defaults, ":keyint=%d",
1137       ARG_KEYINT_MAX_DEFAULT);
1138   g_object_class_install_property (gobject_class, ARG_CABAC,
1139       g_param_spec_boolean ("cabac", "Use CABAC", "Enable CABAC entropy coding",
1140           ARG_CABAC_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1141   g_string_append_printf (x264enc_defaults, ":cabac=%d", ARG_CABAC_DEFAULT);
1142   g_object_class_install_property (gobject_class, ARG_QP_MIN,
1143       g_param_spec_uint ("qp-min", "Minimum Quantizer",
1144           "Minimum quantizer", 0, 63, ARG_QP_MIN_DEFAULT,
1145           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1146   g_string_append_printf (x264enc_defaults, ":qpmin=%d", ARG_QP_MIN_DEFAULT);
1147   g_object_class_install_property (gobject_class, ARG_QP_MAX,
1148       g_param_spec_uint ("qp-max", "Maximum Quantizer",
1149           "Maximum quantizer", 0, 63, ARG_QP_MAX_DEFAULT,
1150           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1151   g_string_append_printf (x264enc_defaults, ":qpmax=%d", ARG_QP_MAX_DEFAULT);
1152   g_object_class_install_property (gobject_class, ARG_QP_STEP,
1153       g_param_spec_uint ("qp-step", "Maximum Quantizer Difference",
1154           "Maximum quantizer difference between frames",
1155           0, 63, ARG_QP_STEP_DEFAULT,
1156           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1157   g_string_append_printf (x264enc_defaults, ":qpstep=%d", ARG_QP_STEP_DEFAULT);
1158   g_object_class_install_property (gobject_class, ARG_IP_FACTOR,
1159       g_param_spec_float ("ip-factor", "IP-Factor",
1160           "Quantizer factor between I- and P-frames",
1161           0, 2, ARG_IP_FACTOR_DEFAULT,
1162           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1163   g_string_append_printf (x264enc_defaults, ":ip-factor=%f",
1164       ARG_IP_FACTOR_DEFAULT);
1165   g_object_class_install_property (gobject_class, ARG_PB_FACTOR,
1166       g_param_spec_float ("pb-factor", "PB-Factor",
1167           "Quantizer factor between P- and B-frames", 0, 2,
1168           ARG_PB_FACTOR_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1169   g_string_append_printf (x264enc_defaults, ":pb-factor=%f",
1170       ARG_PB_FACTOR_DEFAULT);
1171   g_object_class_install_property (gobject_class, ARG_RC_MB_TREE,
1172       g_param_spec_boolean ("mb-tree", "Macroblock Tree",
1173           "Macroblock-Tree ratecontrol",
1174           ARG_RC_MB_TREE_DEFAULT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1175   g_string_append_printf (x264enc_defaults, ":mbtree=%d",
1176       ARG_RC_MB_TREE_DEFAULT);
1177   g_object_class_install_property (gobject_class, ARG_RC_LOOKAHEAD,
1178       g_param_spec_int ("rc-lookahead", "Rate Control Lookahead",
1179           "Number of frames for frametype lookahead", 0, 250,
1180           ARG_RC_LOOKAHEAD_DEFAULT,
1181           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1182   g_string_append_printf (x264enc_defaults, ":rc-lookahead=%d",
1183       ARG_RC_LOOKAHEAD_DEFAULT);
1184   g_object_class_install_property (gobject_class, ARG_NR,
1185       g_param_spec_uint ("noise-reduction", "Noise Reduction",
1186           "Noise reduction strength",
1187           0, 100000, ARG_NR_DEFAULT,
1188           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1189   g_string_append_printf (x264enc_defaults, ":nr=%d", ARG_NR_DEFAULT);
1190   g_object_class_install_property (gobject_class, ARG_INTERLACED,
1191       g_param_spec_boolean ("interlaced", "Interlaced",
1192           "Interlaced material", ARG_INTERLACED_DEFAULT,
1193           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1194   g_string_append_printf (x264enc_defaults, ":interlaced=%d",
1195       ARG_INTERLACED_DEFAULT);
1196
1197   /* append deblock parameters */
1198   g_string_append_printf (x264enc_defaults, ":deblock=0,0");
1199   /* append weighted prediction parameter */
1200   g_string_append_printf (x264enc_defaults, ":weightp=0");
1201
1202   gst_element_class_set_static_metadata (element_class,
1203       "x264 H.264 Encoder", "Codec/Encoder/Video",
1204       "libx264-based H.264 video encoder",
1205       "Josef Zlomek <josef.zlomek@itonis.tv>, "
1206       "Mark Nauwelaerts <mnauw@users.sf.net>");
1207
1208   supported_sinkcaps = gst_caps_new_simple ("video/x-raw",
1209       "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1,
1210       "width", GST_TYPE_INT_RANGE, 1, G_MAXINT,
1211       "height", GST_TYPE_INT_RANGE, 1, G_MAXINT, NULL);
1212
1213   gst_x264_enc_add_x264_chroma_format (gst_caps_get_structure
1214       (supported_sinkcaps, 0), TRUE, TRUE, TRUE, TRUE);
1215
1216   sink_templ = gst_pad_template_new ("sink",
1217       GST_PAD_SINK, GST_PAD_ALWAYS, supported_sinkcaps);
1218
1219   gst_caps_unref (supported_sinkcaps);
1220
1221   gst_element_class_add_pad_template (element_class, sink_templ);
1222   gst_element_class_add_static_pad_template (element_class, &src_factory);
1223
1224   gst_type_mark_as_plugin_api (GST_X264_ENC_ANALYSE_TYPE, 0);
1225   gst_type_mark_as_plugin_api (GST_X264_ENC_FRAME_PACKING_TYPE, 0);
1226   gst_type_mark_as_plugin_api (GST_X264_ENC_ME_TYPE, 0);
1227   gst_type_mark_as_plugin_api (GST_X264_ENC_PASS_TYPE, 0);
1228   gst_type_mark_as_plugin_api (GST_X264_ENC_PSY_TUNE_TYPE, 0);
1229   gst_type_mark_as_plugin_api (GST_X264_ENC_SPEED_PRESET_TYPE, 0);
1230   gst_type_mark_as_plugin_api (GST_X264_ENC_TUNE_TYPE, 0);
1231 }
1232
1233 /* *INDENT-OFF* */
1234 G_GNUC_PRINTF (3, 0)
1235 /* *INDENT-ON* */
1236
1237 static void
1238 gst_x264_enc_log_callback (gpointer private, gint level, const char *format,
1239     va_list args)
1240 {
1241 #ifndef GST_DISABLE_GST_DEBUG
1242   GstDebugLevel gst_level;
1243   GObject *object = (GObject *) private;
1244   gchar *formatted;
1245
1246   switch (level) {
1247     case X264_LOG_NONE:
1248       gst_level = GST_LEVEL_NONE;
1249       break;
1250     case X264_LOG_ERROR:
1251       gst_level = GST_LEVEL_ERROR;
1252       break;
1253     case X264_LOG_WARNING:
1254       gst_level = GST_LEVEL_WARNING;
1255       break;
1256     case X264_LOG_INFO:
1257       gst_level = GST_LEVEL_INFO;
1258       break;
1259     default:
1260       /* push x264enc debug down to our lower levels to avoid some clutter */
1261       gst_level = GST_LEVEL_LOG;
1262       break;
1263   }
1264
1265   if (G_LIKELY (gst_level > _gst_debug_min))
1266     return;
1267
1268   if (G_LIKELY (gst_level > gst_debug_category_get_threshold (GST_CAT_DEFAULT)))
1269     return;
1270
1271   formatted = g_strdup_vprintf (format, args);
1272   g_strchomp (formatted);
1273
1274   GST_CAT_LEVEL_LOG (GST_CAT_DEFAULT, gst_level, object, "%s", formatted);
1275
1276   g_free (formatted);
1277 #endif /* GST_DISABLE_GST_DEBUG */
1278 }
1279
1280 /* initialize the new element
1281  * instantiate pads and add them to element
1282  * set functions
1283  * initialize structure
1284  */
1285 static void
1286 gst_x264_enc_init (GstX264Enc * encoder)
1287 {
1288   /* properties */
1289   encoder->threads = ARG_THREADS_DEFAULT;
1290   encoder->sliced_threads = ARG_SLICED_THREADS_DEFAULT;
1291   encoder->sync_lookahead = ARG_SYNC_LOOKAHEAD_DEFAULT;
1292   encoder->pass = ARG_PASS_DEFAULT;
1293   encoder->quantizer = ARG_QUANTIZER_DEFAULT;
1294   encoder->mp_cache_file = g_strdup (ARG_MULTIPASS_CACHE_FILE_DEFAULT);
1295   encoder->byte_stream = ARG_BYTE_STREAM_DEFAULT;
1296   encoder->intra_refresh = ARG_INTRA_REFRESH_DEFAULT;
1297   encoder->vbv_buf_capacity = ARG_VBV_BUF_CAPACITY_DEFAULT;
1298   encoder->me = ARG_ME_DEFAULT;
1299   encoder->subme = ARG_SUBME_DEFAULT;
1300   encoder->analyse = ARG_ANALYSE_DEFAULT;
1301   encoder->dct8x8 = ARG_DCT8x8_DEFAULT;
1302   encoder->ref = ARG_REF_DEFAULT;
1303   encoder->bframes = ARG_BFRAMES_DEFAULT;
1304   encoder->b_adapt = ARG_B_ADAPT_DEFAULT;
1305   encoder->b_pyramid = ARG_B_PYRAMID_DEFAULT;
1306   encoder->weightb = ARG_WEIGHTB_DEFAULT;
1307   encoder->sps_id = ARG_SPS_ID_DEFAULT;
1308   encoder->au_nalu = ARG_AU_NALU_DEFAULT;
1309   encoder->trellis = ARG_TRELLIS_DEFAULT;
1310   encoder->keyint_max = ARG_KEYINT_MAX_DEFAULT;
1311   encoder->cabac = ARG_CABAC_DEFAULT;
1312   encoder->qp_min = ARG_QP_MIN_DEFAULT;
1313   encoder->qp_max = ARG_QP_MAX_DEFAULT;
1314   encoder->qp_step = ARG_QP_STEP_DEFAULT;
1315   encoder->ip_factor = ARG_IP_FACTOR_DEFAULT;
1316   encoder->pb_factor = ARG_PB_FACTOR_DEFAULT;
1317   encoder->mb_tree = ARG_RC_MB_TREE_DEFAULT;
1318   encoder->rc_lookahead = ARG_RC_LOOKAHEAD_DEFAULT;
1319   encoder->noise_reduction = ARG_NR_DEFAULT;
1320   encoder->interlaced = ARG_INTERLACED_DEFAULT;
1321   encoder->option_string = g_string_new (NULL);
1322   encoder->option_string_prop = g_string_new (ARG_OPTION_STRING_DEFAULT);
1323   encoder->speed_preset = ARG_SPEED_PRESET_DEFAULT;
1324   encoder->psy_tune = ARG_PSY_TUNE_DEFAULT;
1325   encoder->tune = ARG_TUNE_DEFAULT;
1326   encoder->frame_packing = ARG_FRAME_PACKING_DEFAULT;
1327   encoder->insert_vui = ARG_INSERT_VUI_DEFAULT;
1328
1329   encoder->bitrate_manager =
1330       gst_encoder_bitrate_profile_manager_new (ARG_BITRATE_DEFAULT);
1331 }
1332
1333 typedef struct
1334 {
1335   GstVideoCodecFrame *frame;
1336   GstVideoFrame vframe;
1337 } FrameData;
1338
1339 static FrameData *
1340 gst_x264_enc_queue_frame (GstX264Enc * enc, GstVideoCodecFrame * frame,
1341     GstVideoInfo * info)
1342 {
1343   GstVideoFrame vframe;
1344   FrameData *fdata;
1345
1346   if (!gst_video_frame_map (&vframe, info, frame->input_buffer, GST_MAP_READ))
1347     return NULL;
1348
1349   fdata = g_slice_new (FrameData);
1350   fdata->frame = gst_video_codec_frame_ref (frame);
1351   fdata->vframe = vframe;
1352
1353   enc->pending_frames = g_list_prepend (enc->pending_frames, fdata);
1354
1355   return fdata;
1356 }
1357
1358 static void
1359 gst_x264_enc_dequeue_frame (GstX264Enc * enc, GstVideoCodecFrame * frame)
1360 {
1361   GList *l;
1362
1363   for (l = enc->pending_frames; l; l = l->next) {
1364     FrameData *fdata = l->data;
1365
1366     if (fdata->frame != frame)
1367       continue;
1368
1369     gst_video_frame_unmap (&fdata->vframe);
1370     gst_video_codec_frame_unref (fdata->frame);
1371     g_slice_free (FrameData, fdata);
1372
1373     enc->pending_frames = g_list_delete_link (enc->pending_frames, l);
1374     return;
1375   }
1376 }
1377
1378 static void
1379 gst_x264_enc_dequeue_all_frames (GstX264Enc * enc)
1380 {
1381   GList *l;
1382
1383   for (l = enc->pending_frames; l; l = l->next) {
1384     FrameData *fdata = l->data;
1385
1386     gst_video_frame_unmap (&fdata->vframe);
1387     gst_video_codec_frame_unref (fdata->frame);
1388     g_slice_free (FrameData, fdata);
1389   }
1390   g_list_free (enc->pending_frames);
1391   enc->pending_frames = NULL;
1392 }
1393
1394 static gboolean
1395 gst_x264_enc_start (GstVideoEncoder * encoder)
1396 {
1397   GstX264Enc *x264enc = GST_X264_ENC (encoder);
1398
1399   x264enc->current_byte_stream = GST_X264_ENC_STREAM_FORMAT_FROM_PROPERTY;
1400
1401   /* make sure that we have enough time for first DTS,
1402      this is probably overkill for most streams */
1403   gst_video_encoder_set_min_pts (encoder, GST_SECOND * 60 * 60 * 1000);
1404
1405   return TRUE;
1406 }
1407
1408 static gboolean
1409 gst_x264_enc_stop (GstVideoEncoder * encoder)
1410 {
1411   GstX264Enc *x264enc = GST_X264_ENC (encoder);
1412
1413   gst_x264_enc_flush_frames (x264enc, FALSE);
1414   gst_x264_enc_close_encoder (x264enc);
1415   gst_x264_enc_dequeue_all_frames (x264enc);
1416
1417   if (x264enc->input_state)
1418     gst_video_codec_state_unref (x264enc->input_state);
1419   x264enc->input_state = NULL;
1420
1421   return TRUE;
1422 }
1423
1424
1425 static gboolean
1426 gst_x264_enc_flush (GstVideoEncoder * encoder)
1427 {
1428   GstX264Enc *x264enc = GST_X264_ENC (encoder);
1429
1430   gst_x264_enc_flush_frames (x264enc, FALSE);
1431   gst_x264_enc_close_encoder (x264enc);
1432   gst_x264_enc_dequeue_all_frames (x264enc);
1433
1434   gst_x264_enc_init_encoder (x264enc);
1435
1436   return TRUE;
1437 }
1438
1439 static void
1440 gst_x264_enc_finalize (GObject * object)
1441 {
1442   GstX264Enc *encoder = GST_X264_ENC (object);
1443
1444   if (encoder->input_state)
1445     gst_video_codec_state_unref (encoder->input_state);
1446   encoder->input_state = NULL;
1447
1448 #define FREE_STRING(ptr) \
1449   if (ptr) \
1450     g_string_free (ptr, TRUE);
1451
1452   FREE_STRING (encoder->tunings);
1453   FREE_STRING (encoder->option_string);
1454   FREE_STRING (encoder->option_string_prop);
1455   gst_encoder_bitrate_profile_manager_free (encoder->bitrate_manager);
1456
1457 #undef FREE_STRING
1458
1459   g_free (encoder->mp_cache_file);
1460   encoder->mp_cache_file = NULL;
1461
1462   gst_x264_enc_close_encoder (encoder);
1463
1464   G_OBJECT_CLASS (parent_class)->finalize (object);
1465 }
1466
1467 /*
1468  * gst_x264_enc_parse_options
1469  * @encoder: Encoder to which options are assigned
1470  * @str: Option string
1471  *
1472  * Parse option string and assign to x264 parameters
1473  *
1474  */
1475 static gboolean
1476 gst_x264_enc_parse_options (GstX264Enc * encoder, const gchar * str)
1477 {
1478   GStrv kvpairs;
1479   guint npairs, i;
1480   gint parse_result = 0, ret = 0;
1481   gchar *options = (gchar *) str;
1482
1483   while (*options == ':')
1484     options++;
1485
1486   kvpairs = g_strsplit (options, ":", 0);
1487   npairs = g_strv_length (kvpairs);
1488
1489   for (i = 0; i < npairs; i++) {
1490     GStrv key_val = g_strsplit (kvpairs[i], "=", 2);
1491
1492     parse_result =
1493         encoder->vtable->x264_param_parse (&encoder->x264param, key_val[0],
1494         key_val[1]);
1495
1496     if (parse_result == X264_PARAM_BAD_NAME) {
1497       GST_ERROR_OBJECT (encoder, "Bad name for option %s=%s",
1498           key_val[0] ? key_val[0] : "", key_val[1] ? key_val[1] : "");
1499     }
1500     if (parse_result == X264_PARAM_BAD_VALUE) {
1501       GST_ERROR_OBJECT (encoder,
1502           "Bad value for option %s=%s (Note: a NULL value for a non-boolean triggers this)",
1503           key_val[0] ? key_val[0] : "", key_val[1] ? key_val[1] : "");
1504     }
1505
1506     g_strfreev (key_val);
1507
1508     if (parse_result)
1509       ret++;
1510   }
1511
1512   g_strfreev (kvpairs);
1513   return !ret;
1514 }
1515
1516 static gint
1517 gst_x264_enc_gst_to_x264_video_format (GstVideoFormat format, gint * nplanes)
1518 {
1519   switch (format) {
1520     case GST_VIDEO_FORMAT_I420:
1521     case GST_VIDEO_FORMAT_YV12:
1522       if (nplanes)
1523         *nplanes = 3;
1524       return X264_CSP_I420;
1525     case GST_VIDEO_FORMAT_I420_10BE:
1526     case GST_VIDEO_FORMAT_I420_10LE:
1527       if (nplanes)
1528         *nplanes = 3;
1529       return X264_CSP_I420 | X264_CSP_HIGH_DEPTH;
1530     case GST_VIDEO_FORMAT_Y42B:
1531       if (nplanes)
1532         *nplanes = 3;
1533       return X264_CSP_I422;
1534     case GST_VIDEO_FORMAT_I422_10BE:
1535     case GST_VIDEO_FORMAT_I422_10LE:
1536       if (nplanes)
1537         *nplanes = 3;
1538       return X264_CSP_I422 | X264_CSP_HIGH_DEPTH;
1539     case GST_VIDEO_FORMAT_Y444:
1540       if (nplanes)
1541         *nplanes = 3;
1542       return X264_CSP_I444;
1543     case GST_VIDEO_FORMAT_Y444_10BE:
1544     case GST_VIDEO_FORMAT_Y444_10LE:
1545       if (nplanes)
1546         *nplanes = 3;
1547       return X264_CSP_I444 | X264_CSP_HIGH_DEPTH;
1548     case GST_VIDEO_FORMAT_NV12:
1549       if (nplanes)
1550         *nplanes = 2;
1551       return X264_CSP_NV12;
1552     default:
1553       g_return_val_if_reached (GST_VIDEO_FORMAT_UNKNOWN);
1554   }
1555 }
1556
1557 /*
1558  * gst_x264_enc_init_encoder
1559  * @encoder:  Encoder which should be initialized.
1560  *
1561  * Initialize x264 encoder.
1562  *
1563  */
1564 static gboolean
1565 gst_x264_enc_init_encoder (GstX264Enc * encoder)
1566 {
1567   guint pass = 0;
1568   GstVideoInfo *info;
1569   guint bitrate;
1570
1571   if (!encoder->input_state) {
1572     GST_DEBUG_OBJECT (encoder, "Have no input state yet");
1573     return FALSE;
1574   }
1575
1576   info = &encoder->input_state->info;
1577
1578   /* make sure that the encoder is closed */
1579   gst_x264_enc_close_encoder (encoder);
1580
1581   GST_OBJECT_LOCK (encoder);
1582
1583   if (GST_VIDEO_INFO_COMP_DEPTH (info, 0) == 8)
1584     encoder->vtable = vtable_8bit;
1585   else if (GST_VIDEO_INFO_COMP_DEPTH (info, 0) == 10)
1586     encoder->vtable = vtable_10bit;
1587
1588   g_assert (encoder->vtable != NULL);
1589
1590   gst_x264_enc_build_tunings_string (encoder);
1591
1592   /* set x264 parameters and use preset/tuning if present */
1593   GST_DEBUG_OBJECT (encoder, "Applying defaults with preset %s, tunings %s",
1594       encoder->speed_preset ? x264_preset_names[encoder->speed_preset - 1] : "",
1595       encoder->tunings && encoder->tunings->len ? encoder->tunings->str : "");
1596   encoder->vtable->x264_param_default_preset (&encoder->x264param,
1597       encoder->speed_preset ? x264_preset_names[encoder->speed_preset -
1598           1] : NULL, encoder->tunings
1599       && encoder->tunings->len ? encoder->tunings->str : NULL);
1600
1601   /* log callback setup; part of parameters
1602    * this needs to be done again after every *param_default* () call */
1603   encoder->x264param.pf_log = gst_x264_enc_log_callback;
1604   encoder->x264param.p_log_private = encoder;
1605   encoder->x264param.i_log_level = X264_LOG_DEBUG;
1606
1607   /* if no preset nor tuning, use property defaults */
1608   if (!encoder->speed_preset && !encoder->tunings->len) {
1609     GST_DEBUG_OBJECT (encoder, "Applying x264enc_defaults");
1610     if (x264enc_defaults->len
1611         && gst_x264_enc_parse_options (encoder,
1612             x264enc_defaults->str) == FALSE) {
1613       GST_DEBUG_OBJECT (encoder,
1614           "x264enc_defaults string contains errors. This is a bug.");
1615       goto unlock_and_return;
1616     }
1617   } else {
1618     /* When using presets we need to respect the default output format */
1619     encoder->x264param.b_aud = encoder->au_nalu;
1620     encoder->x264param.b_annexb = encoder->byte_stream;
1621   }
1622
1623   /* setup appropriate timebase for gstreamer */
1624   encoder->x264param.i_timebase_num = 1;
1625   encoder->x264param.i_timebase_den = 1000000000;
1626
1627   /* apply option-string property */
1628   if (encoder->option_string_prop && encoder->option_string_prop->len) {
1629     GST_DEBUG_OBJECT (encoder, "Applying option-string: %s",
1630         encoder->option_string_prop->str);
1631     if (gst_x264_enc_parse_options (encoder,
1632             encoder->option_string_prop->str) == FALSE) {
1633       GST_DEBUG_OBJECT (encoder, "Your option-string contains errors.");
1634       goto unlock_and_return;
1635     }
1636   }
1637   /* apply user-set options */
1638   if (encoder->option_string && encoder->option_string->len) {
1639     GST_DEBUG_OBJECT (encoder, "Applying user-set options: %s",
1640         encoder->option_string->str);
1641     if (gst_x264_enc_parse_options (encoder,
1642             encoder->option_string->str) == FALSE) {
1643       GST_DEBUG_OBJECT (encoder, "Failed to parse internal option string. "
1644           "This could be due to use of an old libx264 version. Option string "
1645           "was: %s", encoder->option_string->str);
1646     }
1647   }
1648
1649   /* set up encoder parameters */
1650 #if X264_BUILD >= 153
1651   encoder->x264param.i_bitdepth = GST_VIDEO_INFO_COMP_DEPTH (info, 0);
1652 #endif
1653   encoder->x264param.i_csp =
1654       gst_x264_enc_gst_to_x264_video_format (info->finfo->format,
1655       &encoder->x264_nplanes);
1656   if (info->fps_d == 0 || info->fps_n == 0) {
1657     /* No FPS so must use VFR
1658      * This raises latency apparently see http://mewiki.project357.com/wiki/X264_Encoding_Suggestions */
1659     encoder->x264param.b_vfr_input = TRUE;
1660     if (encoder->keyint_max) {  /* NB the default is 250 setup by x264 itself */
1661       encoder->x264param.i_keyint_max = encoder->keyint_max;
1662     }
1663   } else {
1664     /* FPS available so set it up */
1665     encoder->x264param.b_vfr_input = FALSE;
1666     encoder->x264param.i_fps_num = info->fps_n;
1667     encoder->x264param.i_fps_den = info->fps_d;
1668     encoder->x264param.i_keyint_max =
1669         encoder->keyint_max ? encoder->keyint_max : (10 * info->fps_n /
1670         info->fps_d);
1671   }
1672   encoder->x264param.i_width = info->width;
1673   encoder->x264param.i_height = info->height;
1674   if (info->par_d > 0) {
1675     encoder->x264param.vui.i_sar_width = info->par_n;
1676     encoder->x264param.vui.i_sar_height = info->par_d;
1677   }
1678
1679   if ((((info->height == 576) && ((info->width == 720)
1680                   || (info->width == 704) || (info->width == 352)))
1681           || ((info->height == 288) && (info->width == 352)))
1682       && (info->fps_d == 1) && (info->fps_n == 25)) {
1683     encoder->x264param.vui.i_vidformat = 1;     /* PAL */
1684   } else if ((((info->height == 480) && ((info->width == 720)
1685                   || (info->width == 704) || (info->width == 352)))
1686           || ((info->height == 240) && (info->width == 352)))
1687       && (info->fps_d == 1001) && ((info->fps_n == 30000)
1688           || (info->fps_n == 24000))) {
1689     encoder->x264param.vui.i_vidformat = 2;     /* NTSC */
1690   } else {
1691     encoder->x264param.vui.i_vidformat = 5;     /* unspecified */
1692   }
1693
1694   if (!encoder->insert_vui)
1695     goto skip_vui_parameters;
1696
1697   encoder->x264param.vui.i_colorprim =
1698       gst_video_color_primaries_to_iso (info->colorimetry.primaries);
1699
1700   encoder->x264param.vui.i_transfer =
1701       gst_video_transfer_function_to_iso (info->colorimetry.transfer);
1702
1703   encoder->x264param.vui.i_colmatrix =
1704       gst_video_color_matrix_to_iso (info->colorimetry.matrix);
1705
1706   if (info->colorimetry.range == GST_VIDEO_COLOR_RANGE_0_255) {
1707     encoder->x264param.vui.b_fullrange = 1;
1708   } else {
1709     encoder->x264param.vui.b_fullrange = 0;
1710   }
1711
1712   switch (info->chroma_site) {
1713     case GST_VIDEO_CHROMA_SITE_MPEG2:
1714       encoder->x264param.vui.i_chroma_loc = 0;
1715       break;
1716     case GST_VIDEO_CHROMA_SITE_JPEG:
1717       encoder->x264param.vui.i_chroma_loc = 1;
1718       break;
1719     case GST_VIDEO_CHROMA_SITE_V_COSITED:
1720       encoder->x264param.vui.i_chroma_loc = 3;
1721       break;
1722     case GST_VIDEO_CHROMA_SITE_DV:
1723       encoder->x264param.vui.i_chroma_loc = 2;
1724       break;
1725     default:
1726       encoder->x264param.vui.i_chroma_loc = 0;
1727       break;
1728   }
1729
1730 skip_vui_parameters:
1731
1732   encoder->x264param.analyse.b_psnr = 0;
1733
1734   bitrate =
1735       gst_encoder_bitrate_profile_manager_get_bitrate (encoder->bitrate_manager,
1736       encoder->input_state ? &encoder->input_state->info : NULL);
1737
1738   /* FIXME 2.0 make configuration more sane and consistent with x264 cmdline:
1739    * + split pass property into a pass property (pass1/2/3 enum) and rc-method
1740    * + bitrate property should only be used in case of CBR method
1741    * + vbv bitrate/buffer should have separate configuration that is then
1742    *   applied independently of the mode:
1743    *    + either using properties (new) vbv-maxrate and (renamed) vbv-bufsize
1744    *    + or dropping vbv-buf-capacity altogether and simply using option-string
1745    */
1746   switch (encoder->pass) {
1747     case GST_X264_ENC_PASS_QUANT:
1748       encoder->x264param.rc.i_rc_method = X264_RC_CQP;
1749       encoder->x264param.rc.i_qp_constant = encoder->quantizer;
1750       break;
1751     case GST_X264_ENC_PASS_QUAL:
1752       encoder->x264param.rc.i_rc_method = X264_RC_CRF;
1753       encoder->x264param.rc.f_rf_constant = encoder->quantizer;
1754       encoder->x264param.rc.i_vbv_max_bitrate = bitrate;
1755       encoder->x264param.rc.i_vbv_buffer_size
1756           = encoder->x264param.rc.i_vbv_max_bitrate
1757           * encoder->vbv_buf_capacity / 1000;
1758       break;
1759     case GST_X264_ENC_PASS_CBR:
1760     case GST_X264_ENC_PASS_PASS1:
1761     case GST_X264_ENC_PASS_PASS2:
1762     case GST_X264_ENC_PASS_PASS3:
1763     default:
1764       encoder->x264param.rc.i_rc_method = X264_RC_ABR;
1765       encoder->x264param.rc.i_bitrate = bitrate;
1766       encoder->x264param.rc.i_vbv_max_bitrate = bitrate;
1767       encoder->x264param.rc.i_vbv_buffer_size =
1768           encoder->x264param.rc.i_vbv_max_bitrate
1769           * encoder->vbv_buf_capacity / 1000;
1770       pass = encoder->pass & 0xF;
1771       break;
1772   }
1773
1774   switch (pass) {
1775     case 0:
1776       encoder->x264param.rc.b_stat_read = 0;
1777       encoder->x264param.rc.b_stat_write = 0;
1778       break;
1779     case 1:
1780       encoder->x264param.rc.b_stat_read = 0;
1781       encoder->x264param.rc.b_stat_write = 1;
1782       encoder->vtable->x264_param_apply_fastfirstpass (&encoder->x264param);
1783       encoder->x264param.i_frame_reference = 1;
1784       encoder->x264param.analyse.b_transform_8x8 = 0;
1785       encoder->x264param.analyse.inter = 0;
1786       encoder->x264param.analyse.i_me_method = X264_ME_DIA;
1787       encoder->x264param.analyse.i_subpel_refine =
1788           MIN (2, encoder->x264param.analyse.i_subpel_refine);
1789       encoder->x264param.analyse.i_trellis = 0;
1790       encoder->x264param.analyse.b_fast_pskip = 1;
1791       break;
1792     case 2:
1793       encoder->x264param.rc.b_stat_read = 1;
1794       encoder->x264param.rc.b_stat_write = 0;
1795       break;
1796     case 3:
1797       encoder->x264param.rc.b_stat_read = 1;
1798       encoder->x264param.rc.b_stat_write = 1;
1799       break;
1800   }
1801
1802   if (encoder->peer_profile) {
1803     if (encoder->vtable->x264_param_apply_profile (&encoder->x264param,
1804             encoder->peer_profile))
1805       GST_WARNING_OBJECT (encoder, "Bad downstream profile name: %s",
1806           encoder->peer_profile);
1807   }
1808
1809   /* If using an intra profile, all frames are intra frames */
1810   if (encoder->peer_intra_profile)
1811     encoder->x264param.i_keyint_max = encoder->x264param.i_keyint_min = 1;
1812
1813   /* Enforce level limits if they were in the caps */
1814   if (encoder->peer_level_idc != -1) {
1815     gint i;
1816     const x264_level_t *peer_level = NULL;
1817
1818     for (i = 0; (*encoder->vtable->x264_levels)[i].level_idc; i++) {
1819       if (encoder->peer_level_idc ==
1820           (*encoder->vtable->x264_levels)[i].level_idc) {
1821         int mb_width = (info->width + 15) / 16;
1822         int mb_height = (info->height + 15) / 16;
1823         int mbs = mb_width * mb_height;
1824
1825         if ((*encoder->vtable->x264_levels)[i].frame_size < mbs ||
1826             (*encoder->vtable->x264_levels)[i].frame_size * 8 <
1827             mb_width * mb_width
1828             || (*encoder->vtable->x264_levels)[i].frame_size * 8 <
1829             mb_height * mb_height) {
1830           GST_WARNING_OBJECT (encoder,
1831               "Frame size larger than level %d allows",
1832               encoder->peer_level_idc);
1833           break;
1834         }
1835
1836         if (info->fps_d && (*encoder->vtable->x264_levels)[i].mbps
1837             < (gint64) mbs * info->fps_n / info->fps_d) {
1838           GST_WARNING_OBJECT (encoder,
1839               "Macroblock rate higher than level %d allows",
1840               encoder->peer_level_idc);
1841           break;
1842         }
1843
1844         peer_level = &(*encoder->vtable->x264_levels)[i];
1845         break;
1846       }
1847     }
1848
1849     if (!peer_level)
1850       goto unlock_and_return;
1851
1852     encoder->x264param.i_level_idc = peer_level->level_idc;
1853
1854     encoder->x264param.rc.i_bitrate = MIN (encoder->x264param.rc.i_bitrate,
1855         peer_level->bitrate);
1856     encoder->x264param.rc.i_vbv_max_bitrate =
1857         MIN (encoder->x264param.rc.i_vbv_max_bitrate, peer_level->bitrate);
1858     encoder->x264param.rc.i_vbv_buffer_size =
1859         MIN (encoder->x264param.rc.i_vbv_buffer_size, peer_level->cpb);
1860     encoder->x264param.analyse.i_mv_range =
1861         MIN (encoder->x264param.analyse.i_mv_range, peer_level->mv_range);
1862
1863     if (peer_level->frame_only) {
1864       encoder->x264param.b_interlaced = FALSE;
1865       encoder->x264param.b_fake_interlaced = FALSE;
1866     }
1867   }
1868
1869   if (GST_VIDEO_INFO_IS_INTERLACED (info)) {
1870     encoder->x264param.b_interlaced = TRUE;
1871     if (GST_VIDEO_INFO_INTERLACE_MODE (info) == GST_VIDEO_INTERLACE_MODE_MIXED) {
1872       encoder->x264param.b_pic_struct = TRUE;
1873     }
1874     if (GST_VIDEO_INFO_FIELD_ORDER (info) ==
1875         GST_VIDEO_FIELD_ORDER_TOP_FIELD_FIRST) {
1876       encoder->x264param.b_tff = TRUE;
1877     } else {
1878       encoder->x264param.b_tff = FALSE;
1879     }
1880   } else {
1881     encoder->x264param.b_interlaced = FALSE;
1882   }
1883
1884   /* Set 3D frame packing */
1885   if (encoder->frame_packing != GST_VIDEO_MULTIVIEW_MODE_NONE)
1886     encoder->x264param.i_frame_packing = encoder->frame_packing;
1887   else
1888     encoder->x264param.i_frame_packing =
1889         gst_x264_enc_mview_mode_to_frame_packing (GST_VIDEO_INFO_MULTIVIEW_MODE
1890         (info));
1891
1892   GST_DEBUG_OBJECT (encoder, "Stereo frame packing = %d",
1893       encoder->x264param.i_frame_packing);
1894
1895   encoder->reconfig = FALSE;
1896
1897   GST_OBJECT_UNLOCK (encoder);
1898
1899   encoder->x264enc = encoder->vtable->x264_encoder_open (&encoder->x264param);
1900   if (!encoder->x264enc) {
1901     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE,
1902         ("Can not initialize x264 encoder."), (NULL));
1903     return FALSE;
1904   }
1905
1906   return TRUE;
1907
1908 unlock_and_return:
1909   GST_OBJECT_UNLOCK (encoder);
1910   return FALSE;
1911 }
1912
1913 /* gst_x264_enc_close_encoder
1914  * @encoder:  Encoder which should close.
1915  *
1916  * Close x264 encoder.
1917  */
1918 static void
1919 gst_x264_enc_close_encoder (GstX264Enc * encoder)
1920 {
1921   if (encoder->x264enc != NULL) {
1922     encoder->vtable->x264_encoder_close (encoder->x264enc);
1923     encoder->x264enc = NULL;
1924   }
1925   encoder->vtable = NULL;
1926 }
1927
1928 #ifndef GST_DISABLE_GST_DEBUG
1929 static void
1930 gst_x264_enc_parse_sei_userdata_unregistered (GstX264Enc * encoder,
1931     guint8 * sei, guint len, guint8 * uuid)
1932 {
1933   GstByteReader br;
1934   guint32 payloadType;
1935   guint32 payloadSize;
1936   guint8 payload_type_byte, payload_size_byte, payload_uuid;
1937   gint i = 0;
1938   guint8 *sei_msg_payload;
1939   guint remaining, payload_size;
1940
1941   gst_byte_reader_init (&br, sei, len);
1942
1943   payloadType = 0;
1944   do {
1945     if (!gst_byte_reader_get_uint8 (&br, &payload_type_byte)) {
1946       goto failed;
1947     }
1948     payloadType += payload_type_byte;
1949   } while (payload_type_byte == 0xff);
1950
1951   payloadSize = 0;
1952   do {
1953     if (!gst_byte_reader_get_uint8 (&br, &payload_size_byte)) {
1954       goto failed;
1955     }
1956     payloadSize += payload_size_byte;
1957   } while (payload_size_byte == 0xff);
1958
1959   remaining = gst_byte_reader_get_remaining (&br);
1960   payload_size = payloadSize * 8 < remaining ? payloadSize * 8 : remaining;
1961
1962   /* SEI_USER_DATA_UNREGISTERED */
1963   if (payloadType != 5) {
1964     goto failed;
1965   }
1966
1967   GST_INFO_OBJECT (encoder,
1968       "SEI message received: payloadType = %u, payloadSize = %u bits",
1969       payloadType, payload_size);
1970
1971   /* check uuid_iso_iec_11578 */
1972   for (i = 0; i < 16; i++) {
1973     if (!gst_byte_reader_get_uint8 (&br, &payload_uuid)) {
1974       goto failed;
1975     }
1976     if (uuid[i] != payload_uuid)
1977       goto failed;
1978   }
1979   payload_size -= 16;
1980
1981   sei_msg_payload = g_malloc (payload_size + 1);
1982   memcpy (sei_msg_payload, sei + gst_byte_reader_get_pos (&br), payload_size);
1983   sei_msg_payload[payload_size] = 0;
1984   GST_INFO_OBJECT (encoder, "Using x264_encoder info: %s", sei_msg_payload);
1985   g_free (sei_msg_payload);
1986
1987   return;
1988
1989 failed:
1990   GST_WARNING_OBJECT (encoder, "error parsing \"sei_userdata_unregistered\"");
1991 }
1992 #endif /* GST_DISABLE_GST_DEBUG */
1993
1994 static gboolean
1995 gst_x264_enc_set_profile_and_level (GstX264Enc * encoder, GstCaps * caps)
1996 {
1997   x264_nal_t *nal;
1998   int i_nal;
1999   int header_return;
2000   gint i;
2001   guint8 *sps;
2002   GstStructure *s;
2003   const gchar *profile;
2004   GstCaps *allowed_caps;
2005   GstStructure *s2;
2006   const gchar *allowed_profile;
2007
2008   header_return =
2009       encoder->vtable->x264_encoder_headers (encoder->x264enc, &nal, &i_nal);
2010   if (header_return < 0) {
2011     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE, ("Encode x264 header failed."),
2012         ("x264_encoder_headers return code=%d", header_return));
2013     return FALSE;
2014   }
2015
2016   sps = NULL;
2017   for (i = 0; i < i_nal; i++) {
2018     if (nal[i].i_type == NAL_SPS) {
2019       sps = nal[i].p_payload + 4;
2020       /* skip NAL unit type */
2021       sps++;
2022     } else if (nal[i].i_type == NAL_SEI) {
2023 #ifndef GST_DISABLE_GST_DEBUG
2024       guint8 *sei = NULL;
2025       guint skip_bytes = 0;
2026       /* x264 uses hardcoded value for the sei userdata uuid. */
2027       guint8 x264_uuid[16] = {
2028         0xdc, 0x45, 0xe9, 0xbd, 0xe6, 0xd9, 0x48, 0xb7,
2029         0x96, 0x2c, 0xd8, 0x20, 0xd9, 0x23, 0xee, 0xef
2030       };
2031       if (encoder->current_byte_stream ==
2032           GST_X264_ENC_STREAM_FORMAT_BYTE_STREAM) {
2033         skip_bytes = nal[i].b_long_startcode ? 4 : 3;
2034       } else {
2035         skip_bytes = 4;
2036       }
2037       sei = nal[i].p_payload + skip_bytes;
2038       /* skip NAL unit type */
2039       sei++;
2040
2041       gst_x264_enc_parse_sei_userdata_unregistered (encoder, sei,
2042           nal[i].i_payload - (skip_bytes + 1), x264_uuid);
2043 #endif /* GST_DISABLE_GST_DEBUG */
2044     }
2045   }
2046
2047   if (!sps) {
2048     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE, ("Encode x264 header failed."),
2049         ("x264_encoder_headers did not return SPS"));
2050     return FALSE;
2051   }
2052
2053   gst_codec_utils_h264_caps_set_level_and_profile (caps, sps, 3);
2054
2055   /* Constrained baseline is a strict subset of baseline. If downstream
2056    * wanted baseline and we produced constrained baseline, we can just
2057    * set the profile to baseline in the caps to make negotiation happy.
2058    * Same goes for baseline as subset of main profile and main as a subset
2059    * of high profile.
2060    */
2061   s = gst_caps_get_structure (caps, 0);
2062   profile = gst_structure_get_string (s, "profile");
2063
2064   allowed_caps = gst_pad_get_allowed_caps (GST_VIDEO_ENCODER_SRC_PAD (encoder));
2065
2066   if (allowed_caps == NULL)
2067     goto no_peer;
2068
2069   if (!gst_caps_can_intersect (allowed_caps, caps)) {
2070     allowed_caps = gst_caps_make_writable (allowed_caps);
2071     allowed_caps = gst_caps_truncate (allowed_caps);
2072     s2 = gst_caps_get_structure (allowed_caps, 0);
2073     gst_structure_fixate_field_string (s2, "profile", profile);
2074     allowed_profile = gst_structure_get_string (s2, "profile");
2075     if (!strcmp (allowed_profile, "high")) {
2076       if (!strcmp (profile, "constrained-baseline")
2077           || !strcmp (profile, "baseline") || !strcmp (profile, "main")) {
2078         gst_structure_set (s, "profile", G_TYPE_STRING, "high", NULL);
2079         GST_INFO_OBJECT (encoder, "downstream requested high profile, but "
2080             "encoder will now output %s profile (which is a subset), due "
2081             "to how it's been configured", profile);
2082       }
2083     } else if (!strcmp (allowed_profile, "main")) {
2084       if (!strcmp (profile, "constrained-baseline")
2085           || !strcmp (profile, "baseline")) {
2086         gst_structure_set (s, "profile", G_TYPE_STRING, "main", NULL);
2087         GST_INFO_OBJECT (encoder, "downstream requested main profile, but "
2088             "encoder will now output %s profile (which is a subset), due "
2089             "to how it's been configured", profile);
2090       }
2091     } else if (!strcmp (allowed_profile, "baseline")) {
2092       if (!strcmp (profile, "constrained-baseline"))
2093         gst_structure_set (s, "profile", G_TYPE_STRING, "baseline", NULL);
2094     }
2095   }
2096   gst_caps_unref (allowed_caps);
2097
2098 no_peer:
2099
2100   return TRUE;
2101 }
2102
2103 /*
2104  * Returns: Buffer with the stream headers.
2105  */
2106 static GstBuffer *
2107 gst_x264_enc_header_buf (GstX264Enc * encoder)
2108 {
2109   GstBuffer *buf;
2110   x264_nal_t *nal;
2111   int i_nal;
2112   int header_return;
2113   int i_size;
2114   int nal_size;
2115   gint i;
2116   guint8 *buffer, *sps;
2117   gulong buffer_size;
2118   gint sei_ni, sps_ni, pps_ni;
2119
2120   if (G_UNLIKELY (encoder->x264enc == NULL))
2121     return NULL;
2122
2123   /* Create avcC header. */
2124
2125   header_return =
2126       encoder->vtable->x264_encoder_headers (encoder->x264enc, &nal, &i_nal);
2127   if (header_return < 0) {
2128     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE, ("Encode x264 header failed."),
2129         ("x264_encoder_headers return code=%d", header_return));
2130     return NULL;
2131   }
2132
2133   sei_ni = sps_ni = pps_ni = -1;
2134   for (i = 0; i < i_nal; i++) {
2135     if (nal[i].i_type == NAL_SEI) {
2136       sei_ni = i;
2137     } else if (nal[i].i_type == NAL_SPS) {
2138       sps_ni = i;
2139     } else if (nal[i].i_type == NAL_PPS) {
2140       pps_ni = i;
2141     }
2142   }
2143
2144   /* x264 is expected to return an SEI (some identification info),
2145    * and SPS and PPS */
2146   if (sps_ni == -1 || pps_ni == -1 ||
2147       nal[sps_ni].i_payload < 4 || nal[pps_ni].i_payload < 1) {
2148     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE, (NULL),
2149         ("Unexpected x264 header."));
2150     return NULL;
2151   }
2152
2153   GST_MEMDUMP ("SPS", nal[sps_ni].p_payload, nal[sps_ni].i_payload);
2154   GST_MEMDUMP ("PPS", nal[pps_ni].p_payload, nal[pps_ni].i_payload);
2155   if (sei_ni != -1) {
2156     GST_MEMDUMP ("SEI", nal[sei_ni].p_payload, nal[sei_ni].i_payload);
2157   }
2158
2159   /* nal payloads with emulation_prevention_three_byte, and some header data */
2160   buffer_size = (nal[sps_ni].i_payload + nal[pps_ni].i_payload) * 4 + 100;
2161   buffer = g_malloc (buffer_size);
2162
2163   sps = nal[sps_ni].p_payload + 4;
2164   /* skip NAL unit type */
2165   sps++;
2166
2167   buffer[0] = 1;                /* AVC Decoder Configuration Record ver. 1 */
2168   buffer[1] = sps[0];           /* profile_idc                             */
2169   buffer[2] = sps[1];           /* profile_compability                     */
2170   buffer[3] = sps[2];           /* level_idc                               */
2171   buffer[4] = 0xfc | (4 - 1);   /* nal_length_size_minus1                  */
2172
2173   i_size = 5;
2174
2175   buffer[i_size++] = 0xe0 | 1;  /* number of SPSs */
2176
2177   nal_size = nal[sps_ni].i_payload - 4;
2178   memcpy (buffer + i_size + 2, nal[sps_ni].p_payload + 4, nal_size);
2179
2180   GST_WRITE_UINT16_BE (buffer + i_size, nal_size);
2181   i_size += nal_size + 2;
2182
2183   buffer[i_size++] = 1;         /* number of PPSs */
2184
2185   nal_size = nal[pps_ni].i_payload - 4;
2186   memcpy (buffer + i_size + 2, nal[pps_ni].p_payload + 4, nal_size);
2187
2188   GST_WRITE_UINT16_BE (buffer + i_size, nal_size);
2189   i_size += nal_size + 2;
2190
2191   buf = gst_buffer_new_and_alloc (i_size);
2192   gst_buffer_fill (buf, 0, buffer, i_size);
2193
2194   GST_MEMDUMP ("header", buffer, i_size);
2195   g_free (buffer);
2196
2197   return buf;
2198 }
2199
2200 /* gst_x264_enc_set_src_caps
2201  * Returns: TRUE on success.
2202  */
2203 static gboolean
2204 gst_x264_enc_set_src_caps (GstX264Enc * encoder, GstCaps * caps)
2205 {
2206   GstCaps *outcaps;
2207   GstStructure *structure;
2208   GstVideoCodecState *state;
2209   GstTagList *tags;
2210   guint bitrate =
2211       gst_encoder_bitrate_profile_manager_get_bitrate (encoder->bitrate_manager,
2212       encoder->input_state ? &encoder->input_state->info : NULL);
2213
2214   outcaps = gst_caps_new_empty_simple ("video/x-h264");
2215   structure = gst_caps_get_structure (outcaps, 0);
2216
2217   if (encoder->current_byte_stream == GST_X264_ENC_STREAM_FORMAT_FROM_PROPERTY) {
2218     if (encoder->byte_stream) {
2219       encoder->current_byte_stream = GST_X264_ENC_STREAM_FORMAT_BYTE_STREAM;
2220     } else {
2221       encoder->current_byte_stream = GST_X264_ENC_STREAM_FORMAT_AVC;
2222     }
2223   }
2224   if (encoder->current_byte_stream == GST_X264_ENC_STREAM_FORMAT_AVC) {
2225     GstBuffer *buf = gst_x264_enc_header_buf (encoder);
2226     if (buf != NULL) {
2227       gst_caps_set_simple (outcaps, "codec_data", GST_TYPE_BUFFER, buf, NULL);
2228       gst_buffer_unref (buf);
2229     }
2230     gst_structure_set (structure, "stream-format", G_TYPE_STRING, "avc", NULL);
2231   } else {
2232     gst_structure_set (structure, "stream-format", G_TYPE_STRING, "byte-stream",
2233         NULL);
2234   }
2235   gst_structure_set (structure, "alignment", G_TYPE_STRING, "au", NULL);
2236
2237   if (!gst_x264_enc_set_profile_and_level (encoder, outcaps)) {
2238     gst_caps_unref (outcaps);
2239     return FALSE;
2240   }
2241
2242   state = gst_video_encoder_set_output_state (GST_VIDEO_ENCODER (encoder),
2243       outcaps, encoder->input_state);
2244   GST_DEBUG_OBJECT (encoder, "output caps: %" GST_PTR_FORMAT, state->caps);
2245
2246   /* If set, local frame packing setting overrides any upstream config */
2247   switch (encoder->frame_packing) {
2248     case 0:
2249       GST_VIDEO_INFO_MULTIVIEW_MODE (&state->info) =
2250           GST_VIDEO_MULTIVIEW_MODE_CHECKERBOARD;
2251       break;
2252     case 1:
2253       GST_VIDEO_INFO_MULTIVIEW_MODE (&state->info) =
2254           GST_VIDEO_MULTIVIEW_MODE_COLUMN_INTERLEAVED;
2255       break;
2256     case 2:
2257       GST_VIDEO_INFO_MULTIVIEW_MODE (&state->info) =
2258           GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED;
2259       break;
2260     case 3:
2261       GST_VIDEO_INFO_MULTIVIEW_MODE (&state->info) =
2262           GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE;
2263       break;
2264     case 4:
2265       GST_VIDEO_INFO_MULTIVIEW_MODE (&state->info) =
2266           GST_VIDEO_MULTIVIEW_MODE_TOP_BOTTOM;
2267       break;
2268     case 5:
2269       GST_VIDEO_INFO_MULTIVIEW_MODE (&state->info) =
2270           GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME;
2271       break;
2272     default:
2273       break;
2274   }
2275
2276   gst_video_codec_state_unref (state);
2277
2278   tags = gst_tag_list_new_empty ();
2279   gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_ENCODER, "x264",
2280       GST_TAG_ENCODER_VERSION, X264_BUILD,
2281       GST_TAG_MAXIMUM_BITRATE, bitrate * 1024,
2282       GST_TAG_NOMINAL_BITRATE, bitrate * 1024, NULL);
2283   gst_video_encoder_merge_tags (GST_VIDEO_ENCODER (encoder), tags,
2284       GST_TAG_MERGE_REPLACE);
2285   gst_tag_list_unref (tags);
2286
2287   return TRUE;
2288 }
2289
2290 static void
2291 gst_x264_enc_set_latency (GstX264Enc * encoder)
2292 {
2293   GstVideoInfo *info = &encoder->input_state->info;
2294   gint max_delayed_frames;
2295   GstClockTime latency;
2296
2297   max_delayed_frames =
2298       encoder->vtable->x264_encoder_maximum_delayed_frames (encoder->x264enc);
2299
2300   if (info->fps_n) {
2301     latency = gst_util_uint64_scale_ceil (GST_SECOND * info->fps_d,
2302         max_delayed_frames, info->fps_n);
2303   } else {
2304     /* FIXME: Assume 25fps. This is better than reporting no latency at
2305      * all and then later failing in live pipelines
2306      */
2307     latency = gst_util_uint64_scale_ceil (GST_SECOND * 1,
2308         max_delayed_frames, 25);
2309   }
2310
2311   GST_INFO_OBJECT (encoder,
2312       "Updating latency to %" GST_TIME_FORMAT " (%d frames)",
2313       GST_TIME_ARGS (latency), max_delayed_frames);
2314
2315   gst_video_encoder_set_latency (GST_VIDEO_ENCODER (encoder), latency, latency);
2316 }
2317
2318 static gboolean
2319 gst_x264_enc_set_format (GstVideoEncoder * video_enc,
2320     GstVideoCodecState * state)
2321 {
2322   GstX264Enc *encoder = GST_X264_ENC (video_enc);
2323   GstVideoInfo *info = &state->info;
2324   GstCaps *template_caps;
2325   GstCaps *allowed_caps = NULL;
2326
2327   /* If the encoder is initialized, do not reinitialize it again if not
2328    * necessary */
2329   if (encoder->x264enc) {
2330     GstVideoInfo *old = &encoder->input_state->info;
2331
2332     if (info->finfo->format == old->finfo->format
2333         && info->width == old->width && info->height == old->height
2334         && info->fps_n == old->fps_n && info->fps_d == old->fps_d
2335         && info->par_n == old->par_n && info->par_d == old->par_d) {
2336       gst_video_codec_state_unref (encoder->input_state);
2337       encoder->input_state = gst_video_codec_state_ref (state);
2338       return TRUE;
2339     }
2340
2341     /* clear out pending frames */
2342     gst_x264_enc_flush_frames (encoder, TRUE);
2343
2344     encoder->sps_id++;
2345   }
2346
2347   if (encoder->input_state)
2348     gst_video_codec_state_unref (encoder->input_state);
2349   encoder->input_state = gst_video_codec_state_ref (state);
2350
2351   encoder->peer_profile = NULL;
2352   encoder->peer_intra_profile = FALSE;
2353   encoder->peer_level_idc = -1;
2354
2355   template_caps = gst_static_pad_template_get_caps (&src_factory);
2356   allowed_caps = gst_pad_get_allowed_caps (GST_VIDEO_ENCODER_SRC_PAD (encoder));
2357
2358   /* Output byte-stream if downstream has ANY caps, it's what people expect,
2359    * and it makes more sense too */
2360   if (allowed_caps == template_caps) {
2361     GST_INFO_OBJECT (encoder,
2362         "downstream has ANY caps, outputting byte-stream");
2363     encoder->current_byte_stream = GST_X264_ENC_STREAM_FORMAT_BYTE_STREAM;
2364     g_string_append_printf (encoder->option_string, ":annexb=1");
2365     gst_caps_unref (allowed_caps);
2366   } else if (allowed_caps) {
2367     GstStructure *s;
2368     const gchar *profile;
2369     const gchar *level;
2370     const gchar *stream_format;
2371
2372     if (gst_caps_is_empty (allowed_caps)) {
2373       gst_caps_unref (allowed_caps);
2374       gst_caps_unref (template_caps);
2375       return FALSE;
2376     }
2377
2378     if (gst_caps_is_any (allowed_caps)) {
2379       gst_caps_unref (allowed_caps);
2380       allowed_caps = gst_caps_ref (template_caps);
2381     }
2382
2383     allowed_caps = gst_caps_make_writable (allowed_caps);
2384     allowed_caps = gst_caps_fixate (allowed_caps);
2385     s = gst_caps_get_structure (allowed_caps, 0);
2386
2387     profile = gst_structure_get_string (s, "profile");
2388     if (profile) {
2389       /* FIXME - if libx264 ever adds support for FMO, ASO or redundant slices
2390        * make sure constrained profile has a separate case which disables
2391        * those */
2392       if (g_str_has_suffix (profile, "-intra")) {
2393         encoder->peer_intra_profile = TRUE;
2394       }
2395       if (!strcmp (profile, "constrained-baseline") ||
2396           !strcmp (profile, "baseline")) {
2397         encoder->peer_profile = "baseline";
2398       } else if (g_str_has_prefix (profile, "high-10")) {
2399         encoder->peer_profile = "high10";
2400       } else if (g_str_has_prefix (profile, "high-4:2:2")) {
2401         encoder->peer_profile = "high422";
2402       } else if (g_str_has_prefix (profile, "high-4:4:4")) {
2403         encoder->peer_profile = "high444";
2404       } else if (g_str_has_prefix (profile, "high")) {
2405         encoder->peer_profile = "high";
2406       } else if (!strcmp (profile, "main")) {
2407         encoder->peer_profile = "main";
2408       } else {
2409         g_assert_not_reached ();
2410       }
2411     }
2412
2413     level = gst_structure_get_string (s, "level");
2414     if (level) {
2415       encoder->peer_level_idc = gst_codec_utils_h264_get_level_idc (level);
2416     }
2417
2418     stream_format = gst_structure_get_string (s, "stream-format");
2419     encoder->current_byte_stream = GST_X264_ENC_STREAM_FORMAT_FROM_PROPERTY;
2420     if (stream_format) {
2421       if (!strcmp (stream_format, "avc")) {
2422         encoder->current_byte_stream = GST_X264_ENC_STREAM_FORMAT_AVC;
2423         g_string_append_printf (encoder->option_string, ":annexb=0");
2424       } else if (!strcmp (stream_format, "byte-stream")) {
2425         encoder->current_byte_stream = GST_X264_ENC_STREAM_FORMAT_BYTE_STREAM;
2426         g_string_append_printf (encoder->option_string, ":annexb=1");
2427       } else {
2428         /* means we have both in caps and _FROM_PROPERTY should be the option */
2429       }
2430     }
2431
2432     gst_caps_unref (allowed_caps);
2433   }
2434
2435   gst_caps_unref (template_caps);
2436
2437   if (!gst_x264_enc_init_encoder (encoder))
2438     return FALSE;
2439
2440   if (!gst_x264_enc_set_src_caps (encoder, state->caps)) {
2441     gst_x264_enc_close_encoder (encoder);
2442     return FALSE;
2443   }
2444
2445   gst_x264_enc_set_latency (encoder);
2446
2447   return TRUE;
2448 }
2449
2450 static GstFlowReturn
2451 gst_x264_enc_finish (GstVideoEncoder * encoder)
2452 {
2453   gst_x264_enc_flush_frames (GST_X264_ENC (encoder), TRUE);
2454   return GST_FLOW_OK;
2455 }
2456
2457 static gboolean
2458 gst_x264_enc_propose_allocation (GstVideoEncoder * encoder, GstQuery * query)
2459 {
2460   GstX264Enc *self = GST_X264_ENC (encoder);
2461   GstVideoInfo *info;
2462   guint num_buffers;
2463
2464   gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
2465
2466   if (!self->input_state)
2467     return FALSE;
2468
2469   if (self->vtable == NULL)
2470     return FALSE;
2471
2472   info = &self->input_state->info;
2473   num_buffers =
2474       self->vtable->x264_encoder_maximum_delayed_frames (self->x264enc) + 1;
2475
2476   gst_query_add_allocation_pool (query, NULL, info->size, num_buffers, 0);
2477
2478   return GST_VIDEO_ENCODER_CLASS (parent_class)->propose_allocation (encoder,
2479       query);
2480 }
2481
2482 static void
2483 gst_x264_enc_add_cc (GstBuffer * buffer, x264_picture_t * pic_in)
2484 {
2485   GstVideoCaptionMeta *cc_meta;
2486   gpointer iter = NULL;
2487
2488   while ((cc_meta =
2489           (GstVideoCaptionMeta *) gst_buffer_iterate_meta_filtered (buffer,
2490               &iter, GST_VIDEO_CAPTION_META_API_TYPE))) {
2491     guint i = pic_in->extra_sei.num_payloads;
2492
2493     if (cc_meta->caption_type != GST_VIDEO_CAPTION_TYPE_CEA708_RAW)
2494       continue;
2495
2496     pic_in->extra_sei.num_payloads += 1;
2497
2498     if (!pic_in->extra_sei.payloads)
2499       pic_in->extra_sei.payloads = g_new0 (x264_sei_payload_t, 1);
2500     else
2501       pic_in->extra_sei.payloads =
2502           g_renew (x264_sei_payload_t, pic_in->extra_sei.payloads,
2503           pic_in->extra_sei.num_payloads);
2504
2505     pic_in->extra_sei.sei_free = g_free;
2506
2507     pic_in->extra_sei.payloads[i].payload_size = cc_meta->size + 11;
2508     pic_in->extra_sei.payloads[i].payload =
2509         g_malloc0 (pic_in->extra_sei.payloads[i].payload_size);
2510     pic_in->extra_sei.payloads[i].payload_type = 4;     /* Registered user data */
2511     memcpy (pic_in->extra_sei.payloads[i].payload + 10, cc_meta->data,
2512         cc_meta->size);
2513     pic_in->extra_sei.payloads[i].payload[0] = 181;     /* 8-bits itu_t_t35_country_code */
2514     pic_in->extra_sei.payloads[i].payload[1] = 0;       /* 16-bits itu_t_t35_provider_code */
2515     pic_in->extra_sei.payloads[i].payload[2] = 49;
2516     pic_in->extra_sei.payloads[i].payload[3] = 'G';     /* 32-bits ATSC_user_identifier */
2517     pic_in->extra_sei.payloads[i].payload[4] = 'A';
2518     pic_in->extra_sei.payloads[i].payload[5] = '9';
2519     pic_in->extra_sei.payloads[i].payload[6] = '4';
2520     pic_in->extra_sei.payloads[i].payload[7] = 3;       /* 8-bits ATSC1_data_user_data_type_code */
2521     /* 8-bits:
2522      * 1 bit process_em_data_flag (0)
2523      * 1 bit process_cc_data_flag (1)
2524      * 1 bit additional_data_flag (0)
2525      * 5-bits cc_count
2526      */
2527     pic_in->extra_sei.payloads[i].payload[8] =
2528         ((cc_meta->size / 3) & 0x1f) | 0x40;
2529     pic_in->extra_sei.payloads[i].payload[9] = 255;     /* 8 bits em_data, unused */
2530     pic_in->extra_sei.payloads[i].payload[cc_meta->size + 10] = 255;    /* 8 marker bits */
2531   }
2532 }
2533
2534 /* chain function
2535  * this function does the actual processing
2536  */
2537 static GstFlowReturn
2538 gst_x264_enc_handle_frame (GstVideoEncoder * video_enc,
2539     GstVideoCodecFrame * frame)
2540 {
2541   GstX264Enc *encoder = GST_X264_ENC (video_enc);
2542   GstVideoInfo *info = &encoder->input_state->info;
2543   GstFlowReturn ret;
2544   x264_picture_t pic_in;
2545   gint i_nal, i;
2546   FrameData *fdata;
2547   gint nplanes = encoder->x264_nplanes;
2548
2549   if (G_UNLIKELY (encoder->x264enc == NULL))
2550     goto not_inited;
2551
2552   /* create x264_picture_t from the buffer */
2553   /* mostly taken from mplayer (file ve_x264.c) */
2554
2555   /* set up input picture */
2556   memset (&pic_in, 0, sizeof (pic_in));
2557
2558   fdata = gst_x264_enc_queue_frame (encoder, frame, info);
2559   if (!fdata)
2560     goto invalid_frame;
2561
2562   pic_in.img.i_csp = encoder->x264param.i_csp;
2563   pic_in.img.i_plane = nplanes;
2564   for (i = 0; i < nplanes; i++) {
2565     pic_in.img.plane[i] = GST_VIDEO_FRAME_COMP_DATA (&fdata->vframe, i);
2566     pic_in.img.i_stride[i] = GST_VIDEO_FRAME_COMP_STRIDE (&fdata->vframe, i);
2567   }
2568
2569   pic_in.i_type = X264_TYPE_AUTO;
2570   pic_in.i_pts = frame->pts;
2571   pic_in.opaque = GINT_TO_POINTER (frame->system_frame_number);
2572
2573   if (GST_VIDEO_INFO_INTERLACE_MODE (info) == GST_VIDEO_INTERLACE_MODE_MIXED) {
2574     if ((fdata->vframe.flags & GST_VIDEO_FRAME_FLAG_INTERLACED) == 0) {
2575       pic_in.i_pic_struct = PIC_STRUCT_PROGRESSIVE;
2576     } else if ((fdata->vframe.flags & GST_VIDEO_FRAME_FLAG_RFF) != 0) {
2577       if ((fdata->vframe.flags & GST_VIDEO_FRAME_FLAG_TFF) != 0) {
2578         pic_in.i_pic_struct = PIC_STRUCT_TOP_BOTTOM_TOP;
2579       } else {
2580         pic_in.i_pic_struct = PIC_STRUCT_BOTTOM_TOP_BOTTOM;
2581       }
2582     } else {
2583       if ((fdata->vframe.flags & GST_VIDEO_FRAME_FLAG_TFF) != 0) {
2584         pic_in.i_pic_struct = PIC_STRUCT_TOP_BOTTOM;
2585       } else {
2586         pic_in.i_pic_struct = PIC_STRUCT_BOTTOM_TOP;
2587       }
2588     }
2589   }
2590
2591   gst_x264_enc_add_cc (frame->input_buffer, &pic_in);
2592
2593   ret = gst_x264_enc_encode_frame (encoder, &pic_in, frame, &i_nal, TRUE);
2594
2595   /* input buffer is released later on */
2596   return ret;
2597
2598 /* ERRORS */
2599 not_inited:
2600   {
2601     GST_WARNING_OBJECT (encoder, "Got buffer before set_caps was called");
2602     return GST_FLOW_NOT_NEGOTIATED;
2603   }
2604 invalid_frame:
2605   {
2606     GST_ERROR_OBJECT (encoder, "Failed to map frame");
2607     return GST_FLOW_ERROR;
2608   }
2609 }
2610
2611 static GstFlowReturn
2612 gst_x264_enc_encode_frame (GstX264Enc * encoder, x264_picture_t * pic_in,
2613     GstVideoCodecFrame * input_frame, int *i_nal, gboolean send)
2614 {
2615   GstVideoCodecFrame *frame = NULL;
2616   GstBuffer *out_buf = NULL;
2617   x264_picture_t pic_out;
2618   x264_nal_t *nal;
2619   int i_size;
2620   int encoder_return;
2621   GstFlowReturn ret = GST_FLOW_OK;
2622   guint8 *data;
2623   gboolean update_latency = FALSE;
2624
2625   if (G_UNLIKELY (encoder->x264enc == NULL)) {
2626     if (input_frame)
2627       gst_video_codec_frame_unref (input_frame);
2628     return GST_FLOW_NOT_NEGOTIATED;
2629   }
2630
2631   GST_OBJECT_LOCK (encoder);
2632   if (encoder->reconfig) {
2633     encoder->reconfig = FALSE;
2634     if (encoder->vtable->x264_encoder_reconfig (encoder->x264enc,
2635             &encoder->x264param) < 0)
2636       GST_WARNING_OBJECT (encoder, "Could not reconfigure");
2637     update_latency = TRUE;
2638   }
2639
2640   if (pic_in && input_frame) {
2641     if (GST_VIDEO_CODEC_FRAME_IS_FORCE_KEYFRAME (input_frame)) {
2642       GST_INFO_OBJECT (encoder, "Forcing key frame");
2643       if (encoder->intra_refresh)
2644         encoder->vtable->x264_encoder_intra_refresh (encoder->x264enc);
2645       else
2646         pic_in->i_type = X264_TYPE_IDR;
2647     }
2648   }
2649   GST_OBJECT_UNLOCK (encoder);
2650
2651   if (G_UNLIKELY (update_latency))
2652     gst_x264_enc_set_latency (encoder);
2653
2654   encoder_return = encoder->vtable->x264_encoder_encode (encoder->x264enc,
2655       &nal, i_nal, pic_in, &pic_out);
2656
2657   if (encoder_return < 0) {
2658     GST_ELEMENT_ERROR (encoder, STREAM, ENCODE, ("Encode x264 frame failed."),
2659         ("x264_encoder_encode return code=%d", encoder_return));
2660     ret = GST_FLOW_ERROR;
2661     /* Make sure we finish this frame */
2662     frame = input_frame;
2663     goto out;
2664   }
2665
2666   /* Input frame is now queued */
2667   if (input_frame)
2668     gst_video_codec_frame_unref (input_frame);
2669
2670   if (!*i_nal) {
2671     ret = GST_FLOW_OK;
2672     goto out;
2673   }
2674
2675   i_size = encoder_return;
2676   data = nal[0].p_payload;
2677
2678   frame = gst_video_encoder_get_frame (GST_VIDEO_ENCODER (encoder),
2679       GPOINTER_TO_INT (pic_out.opaque));
2680   g_assert (frame || !send);
2681
2682   if (!send || !frame) {
2683     ret = GST_FLOW_OK;
2684     goto out;
2685   }
2686
2687   out_buf = gst_buffer_new_allocate (NULL, i_size, NULL);
2688   gst_buffer_fill (out_buf, 0, data, i_size);
2689   frame->output_buffer = out_buf;
2690
2691   GST_LOG_OBJECT (encoder,
2692       "output: dts %" G_GINT64_FORMAT " pts %" G_GINT64_FORMAT,
2693       (gint64) pic_out.i_dts, (gint64) pic_out.i_pts);
2694
2695   /* we want to know if x264 is messing around with this */
2696   g_assert (frame->pts == pic_out.i_pts);
2697
2698   frame->dts = pic_out.i_dts;
2699   frame->pts = pic_out.i_pts;
2700
2701   if (pic_out.b_keyframe) {
2702     GST_DEBUG_OBJECT (encoder, "Output keyframe");
2703     GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (frame);
2704   }
2705
2706 out:
2707   if (frame) {
2708     gst_x264_enc_dequeue_frame (encoder, frame);
2709     ret = gst_video_encoder_finish_frame (GST_VIDEO_ENCODER (encoder), frame);
2710   }
2711
2712   return ret;
2713 }
2714
2715 static void
2716 gst_x264_enc_flush_frames (GstX264Enc * encoder, gboolean send)
2717 {
2718   GstFlowReturn flow_ret;
2719   gint i_nal;
2720
2721   /* first send the remaining frames */
2722   if (encoder->x264enc)
2723     do {
2724       flow_ret = gst_x264_enc_encode_frame (encoder, NULL, NULL, &i_nal, send);
2725     } while (flow_ret == GST_FLOW_OK
2726         && encoder->vtable->x264_encoder_delayed_frames (encoder->x264enc) > 0);
2727 }
2728
2729 static void
2730 gst_x264_enc_reconfig (GstX264Enc * encoder)
2731 {
2732   guint bitrate;
2733
2734   if (!encoder->vtable)
2735     return;
2736
2737   bitrate =
2738       gst_encoder_bitrate_profile_manager_get_bitrate (encoder->bitrate_manager,
2739       encoder->input_state ? &encoder->input_state->info : NULL);
2740   switch (encoder->pass) {
2741     case GST_X264_ENC_PASS_QUAL:
2742       encoder->x264param.rc.f_rf_constant = encoder->quantizer;
2743       encoder->x264param.rc.i_vbv_max_bitrate = bitrate;
2744       encoder->x264param.rc.i_vbv_buffer_size
2745           = encoder->x264param.rc.i_vbv_max_bitrate
2746           * encoder->vbv_buf_capacity / 1000;
2747       break;
2748     case GST_X264_ENC_PASS_CBR:
2749     case GST_X264_ENC_PASS_PASS1:
2750     case GST_X264_ENC_PASS_PASS2:
2751     case GST_X264_ENC_PASS_PASS3:
2752     default:
2753       encoder->x264param.rc.i_bitrate = bitrate;
2754       encoder->x264param.rc.i_vbv_max_bitrate = bitrate;
2755       encoder->x264param.rc.i_vbv_buffer_size
2756           = encoder->x264param.rc.i_vbv_max_bitrate
2757           * encoder->vbv_buf_capacity / 1000;
2758       break;
2759   }
2760
2761   encoder->reconfig = TRUE;
2762 }
2763
2764 static void
2765 gst_x264_enc_set_property (GObject * object, guint prop_id,
2766     const GValue * value, GParamSpec * pspec)
2767 {
2768   GstX264Enc *encoder;
2769   GstState state;
2770
2771   const gchar *partitions = NULL;
2772
2773   encoder = GST_X264_ENC (object);
2774
2775   GST_OBJECT_LOCK (encoder);
2776   /* state at least matters for sps, bytestream, pass,
2777    * and so by extension ... */
2778
2779   state = GST_STATE (encoder);
2780   if ((state != GST_STATE_READY && state != GST_STATE_NULL) &&
2781       !(pspec->flags & GST_PARAM_MUTABLE_PLAYING))
2782     goto wrong_state;
2783
2784   switch (prop_id) {
2785     case ARG_PASS:
2786       encoder->pass = g_value_get_enum (value);
2787       break;
2788     case ARG_QUANTIZER:
2789       encoder->quantizer = g_value_get_uint (value);
2790       gst_x264_enc_reconfig (encoder);
2791       break;
2792     case ARG_BITRATE:
2793       gst_encoder_bitrate_profile_manager_set_bitrate (encoder->bitrate_manager,
2794           g_value_get_uint (value));
2795       gst_x264_enc_reconfig (encoder);
2796       break;
2797     case ARG_VBV_BUF_CAPACITY:
2798       encoder->vbv_buf_capacity = g_value_get_uint (value);
2799       gst_x264_enc_reconfig (encoder);
2800       break;
2801     case ARG_SPEED_PRESET:
2802       encoder->speed_preset = g_value_get_enum (value);
2803       break;
2804     case ARG_PSY_TUNE:
2805       encoder->psy_tune = g_value_get_enum (value);
2806       break;
2807     case ARG_TUNE:
2808       encoder->tune = g_value_get_flags (value);
2809       break;
2810     case ARG_OPTION_STRING:
2811       g_string_assign (encoder->option_string_prop, g_value_get_string (value));
2812       break;
2813     case ARG_THREADS:
2814       encoder->threads = g_value_get_uint (value);
2815       g_string_append_printf (encoder->option_string, ":threads=%d",
2816           encoder->threads);
2817       break;
2818     case ARG_SLICED_THREADS:
2819       encoder->sliced_threads = g_value_get_boolean (value);
2820       g_string_append_printf (encoder->option_string, ":sliced-threads=%d",
2821           encoder->sliced_threads);
2822       break;
2823     case ARG_SYNC_LOOKAHEAD:
2824       encoder->sync_lookahead = g_value_get_int (value);
2825       g_string_append_printf (encoder->option_string, ":sync-lookahead=%d",
2826           encoder->sync_lookahead);
2827       break;
2828     case ARG_MULTIPASS_CACHE_FILE:
2829       g_free (encoder->mp_cache_file);
2830       encoder->mp_cache_file = g_value_dup_string (value);
2831       g_string_append_printf (encoder->option_string, ":stats=%s",
2832           encoder->mp_cache_file);
2833       break;
2834     case ARG_BYTE_STREAM:
2835       encoder->byte_stream = g_value_get_boolean (value);
2836       g_string_append_printf (encoder->option_string, ":annexb=%d",
2837           encoder->byte_stream);
2838       break;
2839     case ARG_INTRA_REFRESH:
2840       encoder->intra_refresh = g_value_get_boolean (value);
2841       g_string_append_printf (encoder->option_string, ":intra-refresh=%d",
2842           encoder->intra_refresh);
2843       break;
2844     case ARG_ME:
2845       encoder->me = g_value_get_enum (value);
2846       g_string_append_printf (encoder->option_string, ":me=%s",
2847           x264_motion_est_names[encoder->me]);
2848       break;
2849     case ARG_SUBME:
2850       encoder->subme = g_value_get_uint (value);
2851       g_string_append_printf (encoder->option_string, ":subme=%d",
2852           encoder->subme);
2853       break;
2854     case ARG_ANALYSE:
2855       encoder->analyse = g_value_get_flags (value);
2856       partitions = gst_x264_enc_build_partitions (encoder->analyse);
2857       if (partitions) {
2858         g_string_append_printf (encoder->option_string, ":partitions=%s",
2859             partitions);
2860         g_free ((gpointer) partitions);
2861       }
2862       break;
2863     case ARG_DCT8x8:
2864       encoder->dct8x8 = g_value_get_boolean (value);
2865       g_string_append_printf (encoder->option_string, ":8x8dct=%d",
2866           encoder->dct8x8);
2867       break;
2868     case ARG_REF:
2869       encoder->ref = g_value_get_uint (value);
2870       g_string_append_printf (encoder->option_string, ":ref=%d", encoder->ref);
2871       break;
2872     case ARG_BFRAMES:
2873       encoder->bframes = g_value_get_uint (value);
2874       g_string_append_printf (encoder->option_string, ":bframes=%d",
2875           encoder->bframes);
2876       break;
2877     case ARG_B_ADAPT:
2878       encoder->b_adapt = g_value_get_boolean (value);
2879       g_string_append_printf (encoder->option_string, ":b-adapt=%d",
2880           encoder->b_adapt);
2881       break;
2882     case ARG_B_PYRAMID:
2883       encoder->b_pyramid = g_value_get_boolean (value);
2884       g_string_append_printf (encoder->option_string, ":b-pyramid=%s",
2885           x264_b_pyramid_names[encoder->b_pyramid]);
2886       break;
2887     case ARG_WEIGHTB:
2888       encoder->weightb = g_value_get_boolean (value);
2889       g_string_append_printf (encoder->option_string, ":weightb=%d",
2890           encoder->weightb);
2891       break;
2892     case ARG_SPS_ID:
2893       encoder->sps_id = g_value_get_uint (value);
2894       g_string_append_printf (encoder->option_string, ":sps-id=%d",
2895           encoder->sps_id);
2896       break;
2897     case ARG_AU_NALU:
2898       encoder->au_nalu = g_value_get_boolean (value);
2899       g_string_append_printf (encoder->option_string, ":aud=%d",
2900           encoder->au_nalu);
2901       break;
2902     case ARG_TRELLIS:
2903       encoder->trellis = g_value_get_boolean (value);
2904       g_string_append_printf (encoder->option_string, ":trellis=%d",
2905           encoder->trellis);
2906       break;
2907     case ARG_KEYINT_MAX:
2908       encoder->keyint_max = g_value_get_uint (value);
2909       g_string_append_printf (encoder->option_string, ":keyint=%d",
2910           encoder->keyint_max);
2911       break;
2912     case ARG_CABAC:
2913       encoder->cabac = g_value_get_boolean (value);
2914       g_string_append_printf (encoder->option_string, ":cabac=%d",
2915           encoder->cabac);
2916       break;
2917     case ARG_QP_MIN:
2918       encoder->qp_min = g_value_get_uint (value);
2919       g_string_append_printf (encoder->option_string, ":qpmin=%d",
2920           encoder->qp_min);
2921       break;
2922     case ARG_QP_MAX:
2923       encoder->qp_max = g_value_get_uint (value);
2924       g_string_append_printf (encoder->option_string, ":qpmax=%d",
2925           encoder->qp_max);
2926       break;
2927     case ARG_QP_STEP:
2928       encoder->qp_step = g_value_get_uint (value);
2929       g_string_append_printf (encoder->option_string, ":qpstep=%d",
2930           encoder->qp_step);
2931       break;
2932     case ARG_IP_FACTOR:
2933       encoder->ip_factor = g_value_get_float (value);
2934       g_string_append_printf (encoder->option_string, ":ip-factor=%f",
2935           encoder->ip_factor);
2936       break;
2937     case ARG_PB_FACTOR:
2938       encoder->pb_factor = g_value_get_float (value);
2939       g_string_append_printf (encoder->option_string, ":pb-factor=%f",
2940           encoder->pb_factor);
2941       break;
2942     case ARG_RC_MB_TREE:
2943       encoder->mb_tree = g_value_get_boolean (value);
2944       g_string_append_printf (encoder->option_string, ":mbtree=%d",
2945           encoder->mb_tree);
2946       break;
2947     case ARG_RC_LOOKAHEAD:
2948       encoder->rc_lookahead = g_value_get_int (value);
2949       g_string_append_printf (encoder->option_string, ":rc-lookahead=%d",
2950           encoder->rc_lookahead);
2951       break;
2952     case ARG_NR:
2953       encoder->noise_reduction = g_value_get_uint (value);
2954       g_string_append_printf (encoder->option_string, ":nr=%d",
2955           encoder->noise_reduction);
2956       break;
2957     case ARG_INTERLACED:
2958       encoder->interlaced = g_value_get_boolean (value);
2959       break;
2960     case ARG_FRAME_PACKING:
2961       encoder->frame_packing = g_value_get_enum (value);
2962       break;
2963     case ARG_INSERT_VUI:
2964       encoder->insert_vui = g_value_get_boolean (value);
2965       break;
2966     default:
2967       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2968       break;
2969   }
2970   GST_OBJECT_UNLOCK (encoder);
2971   return;
2972
2973   /* ERROR */
2974 wrong_state:
2975   {
2976     GST_WARNING_OBJECT (encoder, "setting property in wrong state");
2977     GST_OBJECT_UNLOCK (encoder);
2978   }
2979 }
2980
2981 static void
2982 gst_x264_enc_get_property (GObject * object, guint prop_id,
2983     GValue * value, GParamSpec * pspec)
2984 {
2985   GstX264Enc *encoder;
2986
2987   encoder = GST_X264_ENC (object);
2988
2989   GST_OBJECT_LOCK (encoder);
2990   switch (prop_id) {
2991     case ARG_THREADS:
2992       g_value_set_uint (value, encoder->threads);
2993       break;
2994     case ARG_SLICED_THREADS:
2995       g_value_set_boolean (value, encoder->sliced_threads);
2996       break;
2997     case ARG_SYNC_LOOKAHEAD:
2998       g_value_set_int (value, encoder->sync_lookahead);
2999       break;
3000     case ARG_PASS:
3001       g_value_set_enum (value, encoder->pass);
3002       break;
3003     case ARG_QUANTIZER:
3004       g_value_set_uint (value, encoder->quantizer);
3005       break;
3006     case ARG_MULTIPASS_CACHE_FILE:
3007       g_value_set_string (value, encoder->mp_cache_file);
3008       break;
3009     case ARG_BYTE_STREAM:
3010       g_value_set_boolean (value, encoder->byte_stream);
3011       break;
3012     case ARG_BITRATE:
3013       g_value_set_uint (value,
3014           gst_encoder_bitrate_profile_manager_get_bitrate
3015           (encoder->bitrate_manager, NULL));
3016       break;
3017     case ARG_INTRA_REFRESH:
3018       g_value_set_boolean (value, encoder->intra_refresh);
3019       break;
3020     case ARG_VBV_BUF_CAPACITY:
3021       g_value_set_uint (value, encoder->vbv_buf_capacity);
3022       break;
3023     case ARG_ME:
3024       g_value_set_enum (value, encoder->me);
3025       break;
3026     case ARG_SUBME:
3027       g_value_set_uint (value, encoder->subme);
3028       break;
3029     case ARG_ANALYSE:
3030       g_value_set_flags (value, encoder->analyse);
3031       break;
3032     case ARG_DCT8x8:
3033       g_value_set_boolean (value, encoder->dct8x8);
3034       break;
3035     case ARG_REF:
3036       g_value_set_uint (value, encoder->ref);
3037       break;
3038     case ARG_BFRAMES:
3039       g_value_set_uint (value, encoder->bframes);
3040       break;
3041     case ARG_B_ADAPT:
3042       g_value_set_boolean (value, encoder->b_adapt);
3043       break;
3044     case ARG_B_PYRAMID:
3045       g_value_set_boolean (value, encoder->b_pyramid);
3046       break;
3047     case ARG_WEIGHTB:
3048       g_value_set_boolean (value, encoder->weightb);
3049       break;
3050     case ARG_SPS_ID:
3051       g_value_set_uint (value, encoder->sps_id);
3052       break;
3053     case ARG_AU_NALU:
3054       g_value_set_boolean (value, encoder->au_nalu);
3055       break;
3056     case ARG_TRELLIS:
3057       g_value_set_boolean (value, encoder->trellis);
3058       break;
3059     case ARG_KEYINT_MAX:
3060       g_value_set_uint (value, encoder->keyint_max);
3061       break;
3062     case ARG_QP_MIN:
3063       g_value_set_uint (value, encoder->qp_min);
3064       break;
3065     case ARG_QP_MAX:
3066       g_value_set_uint (value, encoder->qp_max);
3067       break;
3068     case ARG_QP_STEP:
3069       g_value_set_uint (value, encoder->qp_step);
3070       break;
3071     case ARG_CABAC:
3072       g_value_set_boolean (value, encoder->cabac);
3073       break;
3074     case ARG_IP_FACTOR:
3075       g_value_set_float (value, encoder->ip_factor);
3076       break;
3077     case ARG_PB_FACTOR:
3078       g_value_set_float (value, encoder->pb_factor);
3079       break;
3080     case ARG_RC_MB_TREE:
3081       g_value_set_boolean (value, encoder->mb_tree);
3082       break;
3083     case ARG_RC_LOOKAHEAD:
3084       g_value_set_int (value, encoder->rc_lookahead);
3085       break;
3086     case ARG_NR:
3087       g_value_set_uint (value, encoder->noise_reduction);
3088       break;
3089     case ARG_INTERLACED:
3090       g_value_set_boolean (value, encoder->interlaced);
3091       break;
3092     case ARG_SPEED_PRESET:
3093       g_value_set_enum (value, encoder->speed_preset);
3094       break;
3095     case ARG_PSY_TUNE:
3096       g_value_set_enum (value, encoder->psy_tune);
3097       break;
3098     case ARG_TUNE:
3099       g_value_set_flags (value, encoder->tune);
3100       break;
3101     case ARG_OPTION_STRING:
3102       g_value_set_string (value, encoder->option_string_prop->str);
3103       break;
3104     case ARG_FRAME_PACKING:
3105       g_value_set_enum (value, encoder->frame_packing);
3106       break;
3107     case ARG_INSERT_VUI:
3108       g_value_set_boolean (value, encoder->insert_vui);
3109       break;
3110     default:
3111       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3112       break;
3113   }
3114   GST_OBJECT_UNLOCK (encoder);
3115 }
3116
3117 static gboolean
3118 x264_element_init (GstPlugin * plugin)
3119 {
3120   GST_DEBUG_CATEGORY_INIT (x264_enc_debug, "x264enc", 0,
3121       "h264 encoding element");
3122
3123   GST_INFO ("linked against x264 build: %u", X264_BUILD);
3124
3125   /* Initialize the static GstX264EncVTable which is overridden in load_x264()
3126    * if needed. We can't initialize statically because these values are not
3127    * constant on Windows. */
3128   default_vtable.module = NULL;
3129 #if X264_BUILD < 153
3130   default_vtable.x264_bit_depth = &x264_bit_depth;
3131 #endif
3132   default_vtable.x264_chroma_format = &x264_chroma_format;
3133   default_vtable.x264_encoder_close = x264_encoder_close;
3134   default_vtable.x264_encoder_delayed_frames = x264_encoder_delayed_frames;
3135   default_vtable.x264_encoder_encode = x264_encoder_encode;
3136   default_vtable.x264_encoder_headers = x264_encoder_headers;
3137   default_vtable.x264_encoder_intra_refresh = x264_encoder_intra_refresh;
3138   default_vtable.x264_encoder_maximum_delayed_frames =
3139       x264_encoder_maximum_delayed_frames;
3140   default_vtable.x264_encoder_open = x264_encoder_open;
3141   default_vtable.x264_encoder_reconfig = x264_encoder_reconfig;
3142   default_vtable.x264_levels = &x264_levels;
3143   default_vtable.x264_param_apply_fastfirstpass =
3144       x264_param_apply_fastfirstpass;
3145   default_vtable.x264_param_apply_profile = x264_param_apply_profile;
3146   default_vtable.x264_param_default_preset = x264_param_default_preset;
3147   default_vtable.x264_param_parse = x264_param_parse;
3148
3149   if (!load_x264_libraries ())
3150     return FALSE;
3151
3152   return gst_element_register (plugin, "x264enc",
3153       GST_RANK_PRIMARY, GST_TYPE_X264_ENC);
3154 }
3155
3156 static gboolean
3157 plugin_init (GstPlugin * plugin)
3158 {
3159   return GST_ELEMENT_REGISTER (x264enc, plugin);
3160 }
3161
3162 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
3163     GST_VERSION_MINOR,
3164     x264,
3165     "libx264-based H.264 encoder plugin",
3166     plugin_init, VERSION, "GPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)