Coverage Report

Created: 2026-11-23 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gstreamer/subprojects/gst-plugins-base/gst-libs/gst/video/gstvideoencoder.c
Line
Count
Source
1
/* GStreamer
2
 * Copyright (C) 2008 David Schleef <ds@schleef.org>
3
 * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>.
4
 * Copyright (C) 2011 Nokia Corporation. All rights reserved.
5
 *   Contact: Stefan Kost <stefan.kost@nokia.com>
6
 * Copyright (C) 2012 Collabora Ltd.
7
 *  Author : Edward Hervey <edward@collabora.com>
8
 *
9
 * This library is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU Library General Public
11
 * License as published by the Free Software Foundation; either
12
 * version 2 of the License, or (at your option) any later version.
13
 *
14
 * This library is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Library General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Library General Public
20
 * License along with this library; if not, write to the
21
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22
 * Boston, MA 02110-1301, USA.
23
 */
24
25
/**
26
 * SECTION:gstvideoencoder
27
 * @title: GstVideoEncoder
28
 * @short_description: Base class for video encoders
29
 *
30
 * This base class is for video encoders turning raw video into
31
 * encoded video data.
32
 *
33
 * GstVideoEncoder and subclass should cooperate as follows.
34
 *
35
 * ## Configuration
36
 *
37
 *   * Initially, GstVideoEncoder calls @start when the encoder element
38
 *     is activated, which allows subclass to perform any global setup.
39
 *   * GstVideoEncoder calls @set_format to inform subclass of the format
40
 *     of input video data that it is about to receive.  Subclass should
41
 *     setup for encoding and configure base class as appropriate
42
 *     (e.g. latency). While unlikely, it might be called more than once,
43
 *     if changing input parameters require reconfiguration.  Baseclass
44
 *     will ensure that processing of current configuration is finished.
45
 *   * GstVideoEncoder calls @stop at end of all processing.
46
 *
47
 * ## Data processing
48
 *
49
 *     * Base class collects input data and metadata into a frame and hands
50
 *       this to subclass' @handle_frame.
51
 *
52
 *     * If codec processing results in encoded data, subclass should call
53
 *       @gst_video_encoder_finish_frame to have encoded data pushed
54
 *       downstream.
55
 *
56
 *     * If implemented, baseclass calls subclass @pre_push just prior to
57
 *       pushing to allow subclasses to modify some metadata on the buffer.
58
 *       If it returns GST_FLOW_OK, the buffer is pushed downstream.
59
 *
60
 *     * GstVideoEncoderClass will handle both srcpad and sinkpad events.
61
 *       Sink events will be passed to subclass if @event callback has been
62
 *       provided.
63
 *
64
 * ## Shutdown phase
65
 *
66
 *   * GstVideoEncoder class calls @stop to inform the subclass that data
67
 *     parsing will be stopped.
68
 *
69
 * Subclass is responsible for providing pad template caps for
70
 * source and sink pads. The pads need to be named "sink" and "src". It should
71
 * also be able to provide fixed src pad caps in @getcaps by the time it calls
72
 * @gst_video_encoder_finish_frame.
73
 *
74
 * Things that subclass need to take care of:
75
 *
76
 *   * Provide pad templates
77
 *   * Provide source pad caps before pushing the first buffer
78
 *   * Accept data in @handle_frame and provide encoded results to
79
 *      @gst_video_encoder_finish_frame.
80
 *
81
 *
82
 * ## Adaptive Presets
83
 *
84
 * #GstVideoEncoder supports adaptive presets, where property values in a
85
 * preset file can vary based on the input video resolution and framerate.
86
 * This is done using GKeyFile's locale string syntax to define alternative
87
 * values for properties.
88
 *
89
 * For example, a preset file can specify different bitrates for different
90
 * resolutions:
91
 *
92
 * ``` ini
93
 * [Profile YouTube]
94
 * bitrate=2500
95
 * bitrate[1920x1080]=8000
96
 * bitrate[1920x1080@48]=12000
97
 * bitrate[3840x2160]=40000
98
 * bitrate[3840x2160@48]=60000
99
 * ```
100
 *
101
 * When a preset with alternatives is loaded, the best matching
102
 * alternative is applied each time the input format changes, before
103
 * the subclass @set_format method runs.
104
 *
105
 * Alternative keys use the format `WxH` (matches when the actual pixel
106
 * count >= W*H) or `WxH@FPS` (additionally requires actual fps >= FPS).
107
 * The most specific match wins (highest pixel count, then highest fps
108
 * threshold). If no alternative matches, the base property value set by
109
 * gst_preset_load_preset() remains.
110
 *
111
 * The #GstVideoEncoder:qos property will enable the Quality-of-Service
112
 * features of the encoder which gather statistics about the real-time
113
 * performance of the downstream elements. If enabled, subclasses can
114
 * use gst_video_encoder_get_max_encode_time() to check if input frames
115
 * are already late and drop them right away to give a chance to the
116
 * pipeline to catch up.
117
 */
118
119
#ifdef HAVE_CONFIG_H
120
#include "config.h"
121
#endif
122
123
/* TODO
124
 *
125
 * * Calculate actual latency based on input/output timestamp/frame_number
126
 *   and if it exceeds the recorded one, save it and emit a GST_MESSAGE_LATENCY
127
 */
128
129
#include <gst/video/video.h>
130
#include "gstvideoencoder.h"
131
#include "gstvideoutils.h"
132
#include "gstvideoutilsprivate.h"
133
134
#include <gst/video/gstvideometa.h>
135
#include <gst/video/gstvideopool.h>
136
137
#include <string.h>
138
#include <stdio.h>
139
140
GST_DEBUG_CATEGORY (videoencoder_debug);
141
#define GST_CAT_DEFAULT videoencoder_debug
142
143
/* properties */
144
145
11
#define DEFAULT_QOS                 FALSE
146
11
#define DEFAULT_MIN_FORCE_KEY_UNIT_INTERVAL 0
147
148
enum
149
{
150
  PROP_0,
151
  PROP_QOS,
152
  PROP_MIN_FORCE_KEY_UNIT_INTERVAL,
153
  PROP_LAST
154
};
155
156
struct _GstVideoEncoderPrivate
157
{
158
  guint64 presentation_frame_number;
159
  int distance_from_sync;
160
161
  /* FIXME : (and introduce a context ?) */
162
  gboolean drained;
163
164
  gint64 min_latency;
165
  gint64 max_latency;
166
167
  /* Tracks whether the latency message was posted at least once */
168
  gboolean posted_latency_msg;
169
170
  /* events that should apply to the current frame */
171
  /* FIXME 2.0: Use a GQueue or similar, see GstVideoCodecFrame::events */
172
  GList *current_frame_events;
173
  /* events that should be pushed before the next frame */
174
  /* FIXME 2.0: Use a GQueue or similar, see GstVideoCodecFrame::events */
175
  GList *pending_events;
176
177
  GList *headers;
178
  gboolean new_headers;         /* Whether new headers were just set */
179
180
  GQueue force_key_unit;        /* List of pending forced keyunits */
181
  GstClockTime min_force_key_unit_interval;
182
  GstClockTime last_force_key_unit_request;
183
  GstClockTime last_key_unit;
184
185
  guint32 system_frame_number;
186
187
  GQueue frames;                /* Protected with OBJECT_LOCK */
188
  GstVideoCodecState *input_state;
189
  GstVideoCodecState *output_state;
190
  gboolean output_state_changed;
191
192
  gint64 bytes;
193
  gint64 time;
194
195
  GstAllocator *allocator;
196
  GstAllocationParams params;
197
198
  /* upstream stream tags (global tags are passed through as-is) */
199
  GstTagList *upstream_tags;
200
201
  /* subclass tags */
202
  GstTagList *tags;
203
  GstTagMergeMode tags_merge_mode;
204
205
  gboolean tags_changed;
206
207
  GstClockTime min_pts;
208
  /* adjustment needed on pts, dts, segment start and stop to accommodate
209
   * min_pts */
210
  GstClockTime time_adjustment;
211
212
  /* QoS properties */
213
  gint qos_enabled;             /* ATOMIC */
214
  gdouble proportion;           /* OBJECT_LOCK */
215
  GstClockTime earliest_time;   /* OBJECT_LOCK */
216
  GstClockTime qos_frame_duration;      /* OBJECT_LOCK */
217
  /* qos messages: frames dropped/processed */
218
  guint dropped;
219
  guint processed;
220
221
  gchar *preset_name;
222
  /* List of GstVideoEncoderAdaptiveProperty */
223
  GList *adaptive_properties;
224
};
225
226
typedef struct _ForcedKeyUnitEvent ForcedKeyUnitEvent;
227
struct _ForcedKeyUnitEvent
228
{
229
  GstClockTime running_time;
230
  gboolean pending;             /* TRUE if this was requested already */
231
  gboolean all_headers;
232
  guint count;
233
  guint32 frame_id;
234
};
235
236
static void
237
forced_key_unit_event_free (ForcedKeyUnitEvent * evt)
238
0
{
239
0
  g_free (evt);
240
0
}
241
242
static ForcedKeyUnitEvent *
243
forced_key_unit_event_new (GstClockTime running_time, gboolean all_headers,
244
    guint count)
245
0
{
246
0
  ForcedKeyUnitEvent *evt = g_new0 (ForcedKeyUnitEvent, 1);
247
248
0
  evt->running_time = running_time;
249
0
  evt->all_headers = all_headers;
250
0
  evt->count = count;
251
252
0
  return evt;
253
0
}
254
255
static gint
256
forced_key_unit_event_compare (const ForcedKeyUnitEvent * a,
257
    const ForcedKeyUnitEvent * b, gpointer user_data)
258
0
{
259
0
  if (a->running_time == b->running_time) {
260
    /* Sort pending ones before non-pending ones */
261
0
    if (a->pending && !b->pending)
262
0
      return -1;
263
0
    if (!a->pending && b->pending)
264
0
      return 1;
265
0
    return 0;
266
0
  }
267
268
0
  if (a->running_time == GST_CLOCK_TIME_NONE)
269
0
    return -1;
270
0
  if (b->running_time == GST_CLOCK_TIME_NONE)
271
0
    return 1;
272
0
  if (a->running_time < b->running_time)
273
0
    return -1;
274
0
  return 1;
275
0
}
276
277
static GstElementClass *parent_class = NULL;
278
static gint private_offset = 0;
279
280
/* cached quark to avoid contention on the global quark table lock */
281
#define META_TAG_VIDEO meta_tag_video_quark
282
static GQuark meta_tag_video_quark;
283
284
static void gst_video_encoder_class_init (GstVideoEncoderClass * klass);
285
static void gst_video_encoder_init (GstVideoEncoder * enc,
286
    GstVideoEncoderClass * klass);
287
288
static void gst_video_encoder_finalize (GObject * object);
289
290
static gboolean gst_video_encoder_setcaps (GstVideoEncoder * enc,
291
    GstCaps * caps);
292
static GstCaps *gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder,
293
    GstCaps * filter);
294
static gboolean gst_video_encoder_src_event (GstPad * pad, GstObject * parent,
295
    GstEvent * event);
296
static gboolean gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
297
    GstEvent * event);
298
static GstFlowReturn gst_video_encoder_chain (GstPad * pad, GstObject * parent,
299
    GstBuffer * buf);
300
static GstStateChangeReturn gst_video_encoder_change_state (GstElement *
301
    element, GstStateChange transition);
302
static gboolean gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
303
    GstQuery * query);
304
static gboolean gst_video_encoder_src_query (GstPad * pad, GstObject * parent,
305
    GstQuery * query);
306
static GstVideoCodecFrame *gst_video_encoder_new_frame (GstVideoEncoder *
307
    encoder, GstBuffer * buf, GstClockTime pts, GstClockTime dts,
308
    GstClockTime duration);
309
310
static gboolean gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
311
    GstEvent * event);
312
static gboolean gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
313
    GstEvent * event);
314
static gboolean gst_video_encoder_default_prepare_allocator (GstVideoEncoder *
315
    encoder, GstCaps * caps);
316
static gboolean gst_video_encoder_decide_allocation_default (GstVideoEncoder *
317
    encoder, GstQuery * query);
318
static gboolean gst_video_encoder_propose_allocation_default (GstVideoEncoder *
319
    encoder, GstQuery * query);
320
static gboolean gst_video_encoder_negotiate_default (GstVideoEncoder * encoder);
321
static gboolean gst_video_encoder_negotiate_unlocked (GstVideoEncoder *
322
    encoder);
323
324
static void gst_video_encoder_post_qos_drop (GstVideoEncoder * enc,
325
    GstVideoCodecFrame * frame);
326
static void gst_video_encoder_push_pending_unlocked (GstVideoEncoder * encoder,
327
    GstVideoCodecFrame * frame, gboolean dropping);
328
329
static gboolean gst_video_encoder_sink_query_default (GstVideoEncoder * encoder,
330
    GstQuery * query);
331
static gboolean gst_video_encoder_src_query_default (GstVideoEncoder * encoder,
332
    GstQuery * query);
333
334
static gboolean gst_video_encoder_transform_meta_default (GstVideoEncoder *
335
    encoder, GstVideoCodecFrame * frame, GstMeta * meta);
336
337
/* Adaptive preset support: parse WxH[@FPS] alternative names and match
338
 * against video info to apply resolution-dependent property values */
339
340
typedef struct
341
{
342
  gchar *alternative_name;      /* e.g. "1920x1080@48" */
343
  guint min_pixels;             /* W*H */
344
  gdouble min_fps;              /* FPS threshold, or 0 */
345
} GstVideoEncoderParsedAlternative;
346
347
typedef struct
348
{
349
  gchar *property_name;
350
  GArray *alternatives;         /* array of GstVideoEncoderParsedAlternative */
351
} GstVideoEncoderAdaptiveProperty;
352
353
typedef gboolean (*LoadPresetFunc) (GstPreset * preset, const gchar * name);
354
355
static LoadPresetFunc parent_load_preset = NULL;
356
357
/* Parse "WxH" or "WxH@FPS"; reject anything else (trailing chars
358
 * included) so unknown alternative-name shapes don't silently match. */
359
static gboolean
360
parse_alternative (const gchar * alt, GstVideoEncoderParsedAlternative * parsed)
361
0
{
362
0
  guint w, h;
363
0
  guint fps;
364
0
  gchar trailing;
365
366
0
  if (sscanf (alt, "%ux%u@%u%c", &w, &h, &fps, &trailing) == 3) {
367
0
    parsed->alternative_name = g_strdup (alt);
368
0
    parsed->min_pixels = w * h;
369
0
    parsed->min_fps = (gdouble) fps;
370
0
    return TRUE;
371
0
  }
372
0
  if (sscanf (alt, "%ux%u%c", &w, &h, &trailing) == 2) {
373
0
    parsed->alternative_name = g_strdup (alt);
374
0
    parsed->min_pixels = w * h;
375
0
    parsed->min_fps = 0.0;
376
0
    return TRUE;
377
0
  }
378
0
  return FALSE;
379
0
}
380
381
static void
382
adaptive_property_free (GstVideoEncoderAdaptiveProperty * prop)
383
0
{
384
0
  guint i;
385
386
0
  g_free (prop->property_name);
387
0
  for (i = 0; i < prop->alternatives->len; i++) {
388
0
    GstVideoEncoderParsedAlternative *alt =
389
0
        &g_array_index (prop->alternatives, GstVideoEncoderParsedAlternative,
390
0
        i);
391
0
    g_free (alt->alternative_name);
392
0
  }
393
0
  g_array_free (prop->alternatives, TRUE);
394
0
  g_free (prop);
395
0
}
396
397
static void
398
gst_video_encoder_clear_adaptive_properties (GstVideoEncoder * encoder)
399
0
{
400
0
  g_free (encoder->priv->preset_name);
401
0
  encoder->priv->preset_name = NULL;
402
0
  g_list_free_full (encoder->priv->adaptive_properties,
403
0
      (GDestroyNotify) adaptive_property_free);
404
0
  encoder->priv->adaptive_properties = NULL;
405
0
}
406
407
static gboolean
408
gst_video_encoder_load_preset (GstPreset * preset, const gchar * name)
409
0
{
410
0
  GstVideoEncoder *encoder = GST_VIDEO_ENCODER (preset);
411
0
  gboolean result;
412
0
  gchar **props;
413
0
  guint i;
414
415
0
  result = parent_load_preset (preset, name);
416
417
0
  GST_OBJECT_LOCK (encoder);
418
0
  gst_video_encoder_clear_adaptive_properties (encoder);
419
420
0
  if (!result) {
421
0
    GST_OBJECT_UNLOCK (encoder);
422
0
    return FALSE;
423
0
  }
424
425
0
  encoder->priv->preset_name = g_strdup (name);
426
427
  /* discover and pre-parse property alternatives */
428
0
  props = gst_preset_get_property_names (preset);
429
0
  if (props) {
430
0
    for (i = 0; props[i]; i++) {
431
0
      gchar **alts =
432
0
          gst_preset_get_property_alternatives (preset, name, props[i]);
433
0
      if (alts) {
434
0
        GstVideoEncoderAdaptiveProperty *adaptive;
435
0
        guint j;
436
437
0
        adaptive = g_new0 (GstVideoEncoderAdaptiveProperty, 1);
438
0
        adaptive->property_name = g_strdup (props[i]);
439
0
        adaptive->alternatives =
440
0
            g_array_new (FALSE, FALSE,
441
0
            sizeof (GstVideoEncoderParsedAlternative));
442
443
0
        for (j = 0; alts[j]; j++) {
444
0
          GstVideoEncoderParsedAlternative parsed;
445
0
          if (parse_alternative (alts[j], &parsed)) {
446
0
            g_array_append_val (adaptive->alternatives, parsed);
447
0
          } else {
448
0
            GST_WARNING_OBJECT (encoder,
449
0
                "Could not parse alternative '%s' for property '%s'",
450
0
                alts[j], props[i]);
451
0
          }
452
0
        }
453
0
        g_strfreev (alts);
454
455
0
        if (adaptive->alternatives->len > 0) {
456
0
          encoder->priv->adaptive_properties =
457
0
              g_list_prepend (encoder->priv->adaptive_properties, adaptive);
458
0
        } else {
459
0
          adaptive_property_free (adaptive);
460
0
        }
461
0
      }
462
0
    }
463
0
    g_strfreev (props);
464
0
  }
465
0
  GST_OBJECT_UNLOCK (encoder);
466
467
0
  return TRUE;
468
0
}
469
470
/* Find the best matching alternative for the given video info.
471
 * Returns the alternative name, or NULL if no match */
472
static const gchar *
473
find_best_alternative (GArray * alternatives, GstVideoInfo * info)
474
0
{
475
0
  gint64 actual_pixels;
476
0
  gdouble actual_fps;
477
0
  guint i;
478
0
  const gchar *best_name = NULL;
479
0
  guint best_pixels = 0;
480
0
  gdouble best_fps = -1.0;
481
482
0
  if (!info || info->finfo == NULL
483
0
      || info->finfo->format == GST_VIDEO_FORMAT_UNKNOWN)
484
0
    return NULL;
485
486
0
  actual_pixels = GST_VIDEO_INFO_WIDTH (info) * GST_VIDEO_INFO_HEIGHT (info);
487
0
  actual_fps =
488
0
      (gdouble) GST_VIDEO_INFO_FPS_N (info) / GST_VIDEO_INFO_FPS_D (info);
489
490
0
  for (i = 0; i < alternatives->len; i++) {
491
0
    GstVideoEncoderParsedAlternative *alt =
492
0
        &g_array_index (alternatives, GstVideoEncoderParsedAlternative, i);
493
494
0
    if (actual_pixels < alt->min_pixels)
495
0
      continue;
496
0
    if (alt->min_fps > 0.0 && actual_fps < alt->min_fps)
497
0
      continue;
498
499
    /* Pick the most specific match: highest pixel count, then highest fps */
500
0
    if (alt->min_pixels > best_pixels ||
501
0
        (alt->min_pixels == best_pixels && alt->min_fps > best_fps)) {
502
0
      best_name = alt->alternative_name;
503
0
      best_pixels = alt->min_pixels;
504
0
      best_fps = alt->min_fps;
505
0
    }
506
0
  }
507
508
0
  return best_name;
509
0
}
510
511
typedef struct
512
{
513
  gchar *property_name;
514
  gchar *key;                   /* "property[alternative]" */
515
} GstVideoEncoderAdaptiveMatch;
516
517
static void
518
gst_video_encoder_apply_adaptive_properties (GstVideoEncoder * encoder,
519
    GstVideoInfo * info)
520
0
{
521
0
  GList *l;
522
0
  GList *matches = NULL;
523
0
  gchar *preset_name;
524
525
0
  GST_OBJECT_LOCK (encoder);
526
527
0
  if (!encoder->priv->adaptive_properties) {
528
0
    GST_OBJECT_UNLOCK (encoder);
529
0
    return;
530
0
  }
531
532
0
  g_assert (encoder->priv->preset_name);
533
0
  preset_name = g_strdup (encoder->priv->preset_name);
534
535
0
  for (l = encoder->priv->adaptive_properties; l; l = l->next) {
536
0
    GstVideoEncoderAdaptiveProperty *prop = l->data;
537
0
    const gchar *best = find_best_alternative (prop->alternatives, info);
538
0
    if (best) {
539
0
      GstVideoEncoderAdaptiveMatch *match =
540
0
          g_new0 (GstVideoEncoderAdaptiveMatch, 1);
541
0
      match->property_name = g_strdup (prop->property_name);
542
0
      match->key = g_strdup_printf ("%s[%s]", prop->property_name, best);
543
0
      matches = g_list_prepend (matches, match);
544
0
    }
545
0
  }
546
547
0
  GST_OBJECT_UNLOCK (encoder);
548
549
0
  for (l = matches; l; l = l->next) {
550
0
    GstVideoEncoderAdaptiveMatch *match = l->data;
551
0
    GValue val = G_VALUE_INIT;
552
553
0
    if (gst_preset_get_property (GST_PRESET (encoder), preset_name,
554
0
            match->key, &val)) {
555
0
      GST_DEBUG_OBJECT (encoder,
556
0
          "adaptive preset: setting %s from alternative %s",
557
0
          match->property_name, match->key);
558
0
      g_object_set_property (G_OBJECT (encoder), match->property_name, &val);
559
0
      g_value_unset (&val);
560
0
    }
561
0
    g_free (match->property_name);
562
0
    g_free (match->key);
563
0
    g_free (match);
564
0
  }
565
0
  g_list_free (matches);
566
0
  g_free (preset_name);
567
0
}
568
569
static void
570
gst_video_encoder_preset_interface_init (GstPresetInterface * iface)
571
11
{
572
11
  parent_load_preset = iface->load_preset;
573
11
  g_assert (parent_load_preset);
574
11
  iface->load_preset = gst_video_encoder_load_preset;
575
11
}
576
577
/* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
578
 * method to get to the padtemplates */
579
GType
580
gst_video_encoder_get_type (void)
581
66
{
582
66
  static gsize type = 0;
583
584
66
  if (g_once_init_enter (&type)) {
585
11
    GType _type;
586
11
    static const GTypeInfo info = {
587
11
      sizeof (GstVideoEncoderClass),
588
11
      NULL,
589
11
      NULL,
590
11
      (GClassInitFunc) gst_video_encoder_class_init,
591
11
      NULL,
592
11
      NULL,
593
11
      sizeof (GstVideoEncoder),
594
11
      0,
595
11
      (GInstanceInitFunc) gst_video_encoder_init,
596
11
    };
597
11
    const GInterfaceInfo preset_interface_info = {
598
11
      (GInterfaceInitFunc) gst_video_encoder_preset_interface_init,
599
11
      NULL,                     /* interface_finalize */
600
      NULL                      /* interface_data */
601
11
    };
602
603
11
    _type = g_type_register_static (GST_TYPE_ELEMENT,
604
11
        "GstVideoEncoder", &info, G_TYPE_FLAG_ABSTRACT);
605
11
    private_offset =
606
11
        g_type_add_instance_private (_type, sizeof (GstVideoEncoderPrivate));
607
11
    g_type_add_interface_static (_type, GST_TYPE_PRESET,
608
11
        &preset_interface_info);
609
11
    g_once_init_leave (&type, _type);
610
11
  }
611
66
  return type;
612
66
}
613
614
static inline GstVideoEncoderPrivate *
615
gst_video_encoder_get_instance_private (GstVideoEncoder * self)
616
0
{
617
0
  return (G_STRUCT_MEMBER_P (self, private_offset));
618
0
}
619
620
static void
621
gst_video_encoder_set_property (GObject * object, guint prop_id,
622
    const GValue * value, GParamSpec * pspec)
623
0
{
624
0
  GstVideoEncoder *sink = GST_VIDEO_ENCODER (object);
625
626
0
  switch (prop_id) {
627
0
    case PROP_QOS:
628
0
      gst_video_encoder_set_qos_enabled (sink, g_value_get_boolean (value));
629
0
      break;
630
0
    case PROP_MIN_FORCE_KEY_UNIT_INTERVAL:
631
0
      gst_video_encoder_set_min_force_key_unit_interval (sink,
632
0
          g_value_get_uint64 (value));
633
0
      break;
634
0
    default:
635
0
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
636
0
      break;
637
0
  }
638
0
}
639
640
static void
641
gst_video_encoder_get_property (GObject * object, guint prop_id, GValue * value,
642
    GParamSpec * pspec)
643
0
{
644
0
  GstVideoEncoder *sink = GST_VIDEO_ENCODER (object);
645
646
0
  switch (prop_id) {
647
0
    case PROP_QOS:
648
0
      g_value_set_boolean (value, gst_video_encoder_is_qos_enabled (sink));
649
0
      break;
650
0
    case PROP_MIN_FORCE_KEY_UNIT_INTERVAL:
651
0
      g_value_set_uint64 (value,
652
0
          gst_video_encoder_get_min_force_key_unit_interval (sink));
653
0
      break;
654
0
    default:
655
0
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
656
0
      break;
657
0
  }
658
0
}
659
660
static void
661
gst_video_encoder_class_init (GstVideoEncoderClass * klass)
662
11
{
663
11
  GObjectClass *gobject_class;
664
11
  GstElementClass *gstelement_class;
665
666
11
  gobject_class = G_OBJECT_CLASS (klass);
667
11
  gstelement_class = GST_ELEMENT_CLASS (klass);
668
669
11
  GST_DEBUG_CATEGORY_INIT (videoencoder_debug, "videoencoder", 0,
670
11
      "Base Video Encoder");
671
672
11
  parent_class = g_type_class_peek_parent (klass);
673
674
11
  if (private_offset != 0)
675
11
    g_type_class_adjust_private_offset (klass, &private_offset);
676
677
11
  gobject_class->set_property = gst_video_encoder_set_property;
678
11
  gobject_class->get_property = gst_video_encoder_get_property;
679
11
  gobject_class->finalize = gst_video_encoder_finalize;
680
681
11
  gstelement_class->change_state =
682
11
      GST_DEBUG_FUNCPTR (gst_video_encoder_change_state);
683
684
11
  klass->sink_event = gst_video_encoder_sink_event_default;
685
11
  klass->src_event = gst_video_encoder_src_event_default;
686
11
  klass->prepare_allocator =
687
11
      GST_DEBUG_FUNCPTR (gst_video_encoder_default_prepare_allocator);
688
11
  klass->propose_allocation = gst_video_encoder_propose_allocation_default;
689
11
  klass->decide_allocation = gst_video_encoder_decide_allocation_default;
690
11
  klass->negotiate = gst_video_encoder_negotiate_default;
691
11
  klass->sink_query = gst_video_encoder_sink_query_default;
692
11
  klass->src_query = gst_video_encoder_src_query_default;
693
11
  klass->transform_meta = gst_video_encoder_transform_meta_default;
694
695
11
  g_object_class_install_property (gobject_class, PROP_QOS,
696
11
      g_param_spec_boolean ("qos", "Qos",
697
11
          "Handle Quality-of-Service events from downstream", DEFAULT_QOS,
698
11
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
699
700
  /**
701
   * GstVideoEncoder:min-force-key-unit-interval:
702
   *
703
   * Minimum interval between force-keyunit requests in nanoseconds. See
704
   * gst_video_encoder_set_min_force_key_unit_interval() for more details.
705
   *
706
   * Since: 1.18
707
   **/
708
11
  g_object_class_install_property (gobject_class,
709
11
      PROP_MIN_FORCE_KEY_UNIT_INTERVAL,
710
11
      g_param_spec_uint64 ("min-force-key-unit-interval",
711
11
          "Minimum Force Keyunit Interval",
712
11
          "Minimum interval between force-keyunit requests in nanoseconds", 0,
713
11
          G_MAXUINT64, DEFAULT_MIN_FORCE_KEY_UNIT_INTERVAL,
714
11
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
715
716
11
  meta_tag_video_quark = g_quark_from_static_string (GST_META_TAG_VIDEO_STR);
717
11
}
718
719
static GList *
720
_flush_events (GstPad * pad, GList * events)
721
0
{
722
0
  GList *tmp;
723
724
0
  for (tmp = events; tmp; tmp = tmp->next) {
725
0
    if (GST_EVENT_TYPE (tmp->data) != GST_EVENT_EOS &&
726
0
        GST_EVENT_TYPE (tmp->data) != GST_EVENT_SEGMENT &&
727
0
        GST_EVENT_IS_STICKY (tmp->data)) {
728
0
      gst_pad_store_sticky_event (pad, GST_EVENT_CAST (tmp->data));
729
0
    }
730
0
    gst_event_unref (tmp->data);
731
0
  }
732
0
  g_list_free (events);
733
734
0
  return NULL;
735
0
}
736
737
static gboolean
738
gst_video_encoder_reset (GstVideoEncoder * encoder, gboolean hard)
739
0
{
740
0
  GstVideoEncoderPrivate *priv = encoder->priv;
741
0
  gboolean ret = TRUE;
742
743
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
744
745
0
  priv->presentation_frame_number = 0;
746
0
  priv->distance_from_sync = 0;
747
748
0
  g_queue_clear_full (&priv->force_key_unit,
749
0
      (GDestroyNotify) forced_key_unit_event_free);
750
0
  priv->last_force_key_unit_request = GST_CLOCK_TIME_NONE;
751
0
  priv->last_key_unit = GST_CLOCK_TIME_NONE;
752
753
0
  priv->drained = TRUE;
754
755
0
  GST_OBJECT_LOCK (encoder);
756
0
  priv->bytes = 0;
757
0
  priv->time = 0;
758
0
  GST_OBJECT_UNLOCK (encoder);
759
760
0
  priv->time_adjustment = GST_CLOCK_TIME_NONE;
761
762
0
  if (hard) {
763
0
    gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
764
0
    gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
765
766
0
    if (priv->input_state)
767
0
      gst_video_codec_state_unref (priv->input_state);
768
0
    priv->input_state = NULL;
769
0
    if (priv->output_state)
770
0
      gst_video_codec_state_unref (priv->output_state);
771
0
    priv->output_state = NULL;
772
773
0
    if (priv->upstream_tags) {
774
0
      gst_tag_list_unref (priv->upstream_tags);
775
0
      priv->upstream_tags = NULL;
776
0
    }
777
0
    if (priv->tags)
778
0
      gst_tag_list_unref (priv->tags);
779
0
    priv->tags = NULL;
780
0
    priv->tags_merge_mode = GST_TAG_MERGE_APPEND;
781
0
    priv->tags_changed = FALSE;
782
783
0
    g_list_foreach (priv->headers, (GFunc) gst_event_unref, NULL);
784
0
    g_list_free (priv->headers);
785
0
    priv->headers = NULL;
786
0
    priv->new_headers = FALSE;
787
788
0
    if (priv->allocator) {
789
0
      gst_object_unref (priv->allocator);
790
0
      priv->allocator = NULL;
791
0
    }
792
793
0
    g_list_free_full (priv->current_frame_events,
794
0
        (GDestroyNotify) gst_event_unref);
795
0
    priv->current_frame_events = NULL;
796
0
    g_list_free_full (priv->pending_events, (GDestroyNotify) gst_event_unref);
797
0
    priv->pending_events = NULL;
798
799
0
    GST_OBJECT_LOCK (encoder);
800
0
    priv->proportion = 0.5;
801
0
    priv->earliest_time = GST_CLOCK_TIME_NONE;
802
0
    priv->qos_frame_duration = 0;
803
0
    GST_OBJECT_UNLOCK (encoder);
804
805
0
    priv->dropped = 0;
806
0
    priv->processed = 0;
807
808
0
    priv->posted_latency_msg = FALSE;
809
0
  } else {
810
0
    GList *l;
811
812
0
    for (l = priv->frames.head; l; l = l->next) {
813
0
      GstVideoCodecFrame *frame = l->data;
814
815
0
      frame->events = _flush_events (encoder->srcpad, frame->events);
816
0
    }
817
0
    priv->current_frame_events = _flush_events (encoder->srcpad,
818
0
        encoder->priv->current_frame_events);
819
0
  }
820
821
0
  g_queue_clear_full (&priv->frames,
822
0
      (GDestroyNotify) gst_video_codec_frame_unref);
823
824
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
825
826
0
  return ret;
827
0
}
828
829
/* Always call reset() in one way or another after this */
830
static gboolean
831
gst_video_encoder_flush (GstVideoEncoder * encoder)
832
0
{
833
0
  GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
834
0
  gboolean ret = TRUE;
835
836
0
  if (klass->flush)
837
0
    ret = klass->flush (encoder);
838
839
0
  return ret;
840
0
}
841
842
static void
843
gst_video_encoder_init (GstVideoEncoder * encoder, GstVideoEncoderClass * klass)
844
0
{
845
0
  GstVideoEncoderPrivate *priv;
846
0
  GstPadTemplate *pad_template;
847
0
  GstPad *pad;
848
849
0
  GST_DEBUG_OBJECT (encoder, "gst_video_encoder_init");
850
851
0
  priv = encoder->priv = gst_video_encoder_get_instance_private (encoder);
852
853
0
  pad_template =
854
0
      gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
855
0
  g_return_if_fail (pad_template != NULL);
856
857
0
  encoder->sinkpad = pad = gst_pad_new_from_template (pad_template, "sink");
858
859
0
  gst_pad_set_chain_function (pad, GST_DEBUG_FUNCPTR (gst_video_encoder_chain));
860
0
  gst_pad_set_event_function (pad,
861
0
      GST_DEBUG_FUNCPTR (gst_video_encoder_sink_event));
862
0
  gst_pad_set_query_function (pad,
863
0
      GST_DEBUG_FUNCPTR (gst_video_encoder_sink_query));
864
0
  gst_element_add_pad (GST_ELEMENT (encoder), encoder->sinkpad);
865
866
0
  pad_template =
867
0
      gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
868
0
  g_return_if_fail (pad_template != NULL);
869
870
0
  encoder->srcpad = pad = gst_pad_new_from_template (pad_template, "src");
871
872
0
  gst_pad_set_query_function (pad,
873
0
      GST_DEBUG_FUNCPTR (gst_video_encoder_src_query));
874
0
  gst_pad_set_event_function (pad,
875
0
      GST_DEBUG_FUNCPTR (gst_video_encoder_src_event));
876
0
  gst_element_add_pad (GST_ELEMENT (encoder), encoder->srcpad);
877
878
0
  gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
879
0
  gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
880
881
0
  g_rec_mutex_init (&encoder->stream_lock);
882
883
0
  priv->headers = NULL;
884
0
  priv->new_headers = FALSE;
885
886
0
  g_queue_init (&priv->frames);
887
0
  g_queue_init (&priv->force_key_unit);
888
889
0
  priv->min_latency = 0;
890
0
  priv->max_latency = 0;
891
0
  priv->min_pts = GST_CLOCK_TIME_NONE;
892
0
  priv->time_adjustment = GST_CLOCK_TIME_NONE;
893
894
0
  gst_video_encoder_reset (encoder, TRUE);
895
0
}
896
897
/**
898
 * gst_video_encoder_set_headers:
899
 * @encoder: a #GstVideoEncoder
900
 * @headers: (transfer full) (element-type GstBuffer): a list of #GstBuffer containing the codec header
901
 *
902
 * Set the codec headers to be sent downstream whenever requested.
903
 */
904
void
905
gst_video_encoder_set_headers (GstVideoEncoder * video_encoder, GList * headers)
906
0
{
907
0
  GST_VIDEO_ENCODER_STREAM_LOCK (video_encoder);
908
909
0
  GST_DEBUG_OBJECT (video_encoder, "new headers %p", headers);
910
0
  if (video_encoder->priv->headers) {
911
0
    g_list_foreach (video_encoder->priv->headers, (GFunc) gst_buffer_unref,
912
0
        NULL);
913
0
    g_list_free (video_encoder->priv->headers);
914
0
  }
915
0
  video_encoder->priv->headers = headers;
916
0
  video_encoder->priv->new_headers = TRUE;
917
918
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (video_encoder);
919
0
}
920
921
static GstVideoCodecState *
922
_new_output_state (GstCaps * caps, GstVideoCodecState * reference)
923
0
{
924
0
  GstVideoCodecState *state;
925
926
0
  state = g_new0 (GstVideoCodecState, 1);
927
0
  g_atomic_ref_count_init ((gatomicrefcount *) & state->ref_count);
928
0
  gst_video_info_init (&state->info);
929
930
0
  if (!gst_video_info_set_format (&state->info, GST_VIDEO_FORMAT_ENCODED, 0, 0)) {
931
0
    g_free (state);
932
0
    return NULL;
933
0
  }
934
935
0
  state->caps = caps;
936
937
0
  if (reference) {
938
0
    GstVideoInfo *tgt, *ref;
939
940
0
    tgt = &state->info;
941
0
    ref = &reference->info;
942
943
    /* Copy over extra fields from reference state */
944
0
    tgt->interlace_mode = ref->interlace_mode;
945
0
    tgt->flags = ref->flags;
946
0
    tgt->width = ref->width;
947
0
    tgt->height = ref->height;
948
0
    tgt->chroma_site = ref->chroma_site;
949
0
    tgt->colorimetry = ref->colorimetry;
950
0
    tgt->par_n = ref->par_n;
951
0
    tgt->par_d = ref->par_d;
952
0
    tgt->fps_n = ref->fps_n;
953
0
    tgt->fps_d = ref->fps_d;
954
955
0
    GST_VIDEO_INFO_FIELD_ORDER (tgt) = GST_VIDEO_INFO_FIELD_ORDER (ref);
956
957
0
    GST_VIDEO_INFO_MULTIVIEW_MODE (tgt) = GST_VIDEO_INFO_MULTIVIEW_MODE (ref);
958
0
    GST_VIDEO_INFO_MULTIVIEW_FLAGS (tgt) = GST_VIDEO_INFO_MULTIVIEW_FLAGS (ref);
959
960
0
    if (reference->mastering_display_info) {
961
0
      state->mastering_display_info =
962
0
          g_memdup2 (reference->mastering_display_info,
963
0
          sizeof (GstVideoMasteringDisplayInfo));
964
0
    }
965
0
    if (reference->content_light_level) {
966
0
      state->content_light_level =
967
0
          g_memdup2 (reference->content_light_level,
968
0
          sizeof (GstVideoContentLightLevel));
969
0
    }
970
0
  }
971
972
0
  return state;
973
0
}
974
975
static GstVideoCodecState *
976
_new_input_state (GstCaps * caps)
977
0
{
978
0
  GstVideoCodecState *state;
979
0
  GstStructure *c_struct;
980
0
  const gchar *s;
981
982
0
  state = g_new0 (GstVideoCodecState, 1);
983
0
  g_atomic_ref_count_init ((gatomicrefcount *) & state->ref_count);
984
0
  gst_video_info_init (&state->info);
985
0
  if (G_UNLIKELY (!gst_video_info_from_caps (&state->info, caps)))
986
0
    goto parse_fail;
987
0
  state->caps = gst_caps_ref (caps);
988
989
0
  c_struct = gst_caps_get_structure (caps, 0);
990
991
0
  if ((s = gst_structure_get_string (c_struct, "mastering-display-info"))) {
992
0
    state->mastering_display_info = g_new (GstVideoMasteringDisplayInfo, 1);
993
0
    gst_video_mastering_display_info_from_string (state->mastering_display_info,
994
0
        s);
995
0
  }
996
0
  if ((s = gst_structure_get_string (c_struct, "content-light-level"))) {
997
0
    state->content_light_level = g_new (GstVideoContentLightLevel, 1);
998
0
    gst_video_content_light_level_from_string (state->content_light_level, s);
999
0
  }
1000
1001
0
  return state;
1002
1003
0
parse_fail:
1004
0
  {
1005
0
    g_free (state);
1006
0
    return NULL;
1007
0
  }
1008
0
}
1009
1010
static gboolean
1011
gst_video_encoder_setcaps (GstVideoEncoder * encoder, GstCaps * caps)
1012
0
{
1013
0
  GstVideoEncoderClass *encoder_class;
1014
0
  GstVideoCodecState *state;
1015
0
  gboolean ret = TRUE;
1016
1017
0
  encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1018
1019
0
  GST_DEBUG_OBJECT (encoder, "setcaps %" GST_PTR_FORMAT, caps);
1020
1021
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1022
1023
0
  if (encoder->priv->input_state) {
1024
0
    GST_DEBUG_OBJECT (encoder,
1025
0
        "Checking if caps changed old %" GST_PTR_FORMAT " new %" GST_PTR_FORMAT,
1026
0
        encoder->priv->input_state->caps, caps);
1027
0
    if (gst_caps_is_equal (encoder->priv->input_state->caps, caps))
1028
0
      goto caps_not_changed;
1029
0
  }
1030
1031
0
  state = _new_input_state (caps);
1032
0
  if (G_UNLIKELY (!state))
1033
0
    goto parse_fail;
1034
1035
0
  if (encoder->priv->input_state
1036
0
      && gst_video_info_is_equal (&state->info,
1037
0
          &encoder->priv->input_state->info)) {
1038
0
    gst_video_codec_state_unref (state);
1039
0
    goto caps_not_changed;
1040
0
  }
1041
1042
0
  if (encoder_class->reset) {
1043
0
    GST_FIXME_OBJECT (encoder, "GstVideoEncoder::reset() is deprecated");
1044
0
    encoder_class->reset (encoder, TRUE);
1045
0
  }
1046
1047
  /* apply adaptive preset properties based on the new format */
1048
0
  gst_video_encoder_apply_adaptive_properties (encoder, &state->info);
1049
1050
  /* and subclass should be ready to configure format at any time around */
1051
0
  if (encoder_class->set_format != NULL)
1052
0
    ret = encoder_class->set_format (encoder, state);
1053
1054
0
  if (ret) {
1055
0
    if (encoder->priv->input_state)
1056
0
      gst_video_codec_state_unref (encoder->priv->input_state);
1057
0
    encoder->priv->input_state = state;
1058
0
  } else {
1059
0
    gst_video_codec_state_unref (state);
1060
0
  }
1061
1062
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1063
1064
0
  if (!ret)
1065
0
    GST_WARNING_OBJECT (encoder, "rejected caps %" GST_PTR_FORMAT, caps);
1066
1067
0
  return ret;
1068
1069
0
caps_not_changed:
1070
0
  {
1071
0
    GST_DEBUG_OBJECT (encoder, "Caps did not change - ignore");
1072
0
    GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1073
0
    return TRUE;
1074
0
  }
1075
1076
  /* ERRORS */
1077
0
parse_fail:
1078
0
  {
1079
0
    GST_WARNING_OBJECT (encoder, "Failed to parse caps");
1080
0
    GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1081
0
    return FALSE;
1082
0
  }
1083
0
}
1084
1085
/**
1086
 * gst_video_encoder_proxy_getcaps:
1087
 * @enc: a #GstVideoEncoder
1088
 * @caps: (nullable): initial caps
1089
 * @filter: (nullable): filter caps
1090
 *
1091
 * Returns caps that express @caps (or sink template caps if @caps == NULL)
1092
 * restricted to resolution/format/... combinations supported by downstream
1093
 * elements (e.g. muxers).
1094
 *
1095
 * Returns: (transfer full): a #GstCaps owned by caller
1096
 */
1097
GstCaps *
1098
gst_video_encoder_proxy_getcaps (GstVideoEncoder * encoder, GstCaps * caps,
1099
    GstCaps * filter)
1100
0
{
1101
0
  return __gst_video_element_proxy_getcaps (GST_ELEMENT_CAST (encoder),
1102
0
      GST_VIDEO_ENCODER_SINK_PAD (encoder),
1103
0
      GST_VIDEO_ENCODER_SRC_PAD (encoder), caps, filter);
1104
0
}
1105
1106
static GstCaps *
1107
gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder, GstCaps * filter)
1108
0
{
1109
0
  GstVideoEncoderClass *klass;
1110
0
  GstCaps *caps;
1111
1112
0
  klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1113
1114
0
  if (klass->getcaps)
1115
0
    caps = klass->getcaps (encoder, filter);
1116
0
  else
1117
0
    caps = gst_video_encoder_proxy_getcaps (encoder, NULL, filter);
1118
1119
0
  GST_LOG_OBJECT (encoder, "Returning caps %" GST_PTR_FORMAT, caps);
1120
1121
0
  return caps;
1122
0
}
1123
1124
static gboolean
1125
gst_video_encoder_decide_allocation_default (GstVideoEncoder * encoder,
1126
    GstQuery * query)
1127
0
{
1128
0
  GstAllocator *allocator = NULL;
1129
0
  GstAllocationParams params;
1130
0
  gboolean update_allocator;
1131
1132
  /* we got configuration from our peer or the decide_allocation method,
1133
   * parse them */
1134
0
  if (gst_query_get_n_allocation_params (query) > 0) {
1135
    /* try the allocator */
1136
0
    gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
1137
0
    update_allocator = TRUE;
1138
0
  } else {
1139
0
    allocator = NULL;
1140
0
    gst_allocation_params_init (&params);
1141
0
    update_allocator = FALSE;
1142
0
  }
1143
1144
0
  if (update_allocator)
1145
0
    gst_query_set_nth_allocation_param (query, 0, allocator, &params);
1146
0
  else
1147
0
    gst_query_add_allocation_param (query, allocator, &params);
1148
0
  if (allocator)
1149
0
    gst_object_unref (allocator);
1150
1151
0
  return TRUE;
1152
0
}
1153
1154
static gboolean
1155
gst_video_encoder_propose_allocation_default (GstVideoEncoder * encoder,
1156
    GstQuery * query)
1157
0
{
1158
0
  GstCaps *caps;
1159
0
  GstVideoInfo info;
1160
0
  GstBufferPool *pool;
1161
0
  guint size;
1162
1163
0
  gst_query_parse_allocation (query, &caps, NULL);
1164
1165
0
  if (caps == NULL)
1166
0
    return FALSE;
1167
1168
0
  if (!gst_video_info_from_caps (&info, caps))
1169
0
    return FALSE;
1170
1171
0
  size = GST_VIDEO_INFO_SIZE (&info);
1172
1173
0
  if (gst_query_get_n_allocation_pools (query) == 0) {
1174
0
    GstStructure *structure;
1175
0
    GstAllocator *allocator = NULL;
1176
0
    GstAllocationParams params = { 0, 15, 0, 0 };
1177
1178
0
    if (gst_query_get_n_allocation_params (query) > 0)
1179
0
      gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
1180
0
    else
1181
0
      gst_query_add_allocation_param (query, allocator, &params);
1182
1183
0
    pool = gst_video_buffer_pool_new ();
1184
0
    {
1185
0
      gchar *name =
1186
0
          g_strdup_printf ("%s-propose-pool", GST_OBJECT_NAME (encoder));
1187
0
      g_object_set (pool, "name", name, NULL);
1188
0
      g_free (name);
1189
0
    }
1190
1191
0
    structure = gst_buffer_pool_get_config (pool);
1192
0
    gst_buffer_pool_config_set_params (structure, caps, size, 0, 0);
1193
0
    gst_buffer_pool_config_set_allocator (structure, allocator, &params);
1194
1195
0
    if (allocator)
1196
0
      gst_object_unref (allocator);
1197
1198
0
    if (!gst_buffer_pool_set_config (pool, structure))
1199
0
      goto config_failed;
1200
1201
0
    gst_query_add_allocation_pool (query, pool, size, 0, 0);
1202
0
    gst_object_unref (pool);
1203
0
    gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
1204
0
  }
1205
1206
0
  return TRUE;
1207
1208
  /* ERRORS */
1209
0
config_failed:
1210
0
  {
1211
0
    GST_ERROR_OBJECT (encoder, "failed to set config");
1212
0
    gst_object_unref (pool);
1213
0
    return FALSE;
1214
0
  }
1215
0
}
1216
1217
static gboolean
1218
gst_video_encoder_sink_query_default (GstVideoEncoder * encoder,
1219
    GstQuery * query)
1220
0
{
1221
0
  GstPad *pad = GST_VIDEO_ENCODER_SINK_PAD (encoder);
1222
0
  gboolean res = FALSE;
1223
1224
0
  switch (GST_QUERY_TYPE (query)) {
1225
0
    case GST_QUERY_CAPS:
1226
0
    {
1227
0
      GstCaps *filter, *caps;
1228
1229
0
      gst_query_parse_caps (query, &filter);
1230
0
      caps = gst_video_encoder_sink_getcaps (encoder, filter);
1231
0
      gst_query_set_caps_result (query, caps);
1232
0
      gst_caps_unref (caps);
1233
0
      res = TRUE;
1234
0
      break;
1235
0
    }
1236
0
    case GST_QUERY_CONVERT:
1237
0
    {
1238
0
      GstFormat src_fmt, dest_fmt;
1239
0
      gint64 src_val, dest_val;
1240
1241
0
      GST_DEBUG_OBJECT (encoder, "convert query");
1242
1243
0
      gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1244
0
      GST_OBJECT_LOCK (encoder);
1245
0
      if (encoder->priv->input_state != NULL)
1246
0
        res = __gst_video_rawvideo_convert (encoder->priv->input_state,
1247
0
            src_fmt, src_val, &dest_fmt, &dest_val);
1248
0
      else
1249
0
        res = FALSE;
1250
0
      GST_OBJECT_UNLOCK (encoder);
1251
0
      if (!res)
1252
0
        goto error;
1253
0
      gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1254
0
      break;
1255
0
    }
1256
0
    case GST_QUERY_ALLOCATION:
1257
0
    {
1258
0
      GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1259
1260
0
      if (klass->propose_allocation)
1261
0
        res = klass->propose_allocation (encoder, query);
1262
0
      break;
1263
0
    }
1264
0
    default:
1265
0
      res = gst_pad_query_default (pad, GST_OBJECT (encoder), query);
1266
0
      break;
1267
0
  }
1268
0
  return res;
1269
1270
0
error:
1271
0
  GST_DEBUG_OBJECT (encoder, "query failed");
1272
0
  return res;
1273
0
}
1274
1275
static gboolean
1276
gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
1277
    GstQuery * query)
1278
0
{
1279
0
  GstVideoEncoder *encoder;
1280
0
  GstVideoEncoderClass *encoder_class;
1281
0
  gboolean ret = FALSE;
1282
1283
0
  encoder = GST_VIDEO_ENCODER (parent);
1284
0
  encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1285
1286
0
  GST_DEBUG_OBJECT (encoder, "received query %d, %s", GST_QUERY_TYPE (query),
1287
0
      GST_QUERY_TYPE_NAME (query));
1288
1289
0
  if (encoder_class->sink_query)
1290
0
    ret = encoder_class->sink_query (encoder, query);
1291
1292
0
  return ret;
1293
0
}
1294
1295
static void
1296
gst_video_encoder_finalize (GObject * object)
1297
0
{
1298
0
  GstVideoEncoder *encoder;
1299
1300
0
  GST_DEBUG_OBJECT (object, "finalize");
1301
1302
0
  encoder = GST_VIDEO_ENCODER (object);
1303
0
  g_rec_mutex_clear (&encoder->stream_lock);
1304
1305
0
  gst_video_encoder_clear_adaptive_properties (encoder);
1306
1307
0
  if (encoder->priv->allocator) {
1308
0
    gst_object_unref (encoder->priv->allocator);
1309
0
    encoder->priv->allocator = NULL;
1310
0
  }
1311
1312
0
  G_OBJECT_CLASS (parent_class)->finalize (object);
1313
0
}
1314
1315
static gboolean
1316
gst_video_encoder_push_event (GstVideoEncoder * encoder, GstEvent * event)
1317
0
{
1318
0
  switch (GST_EVENT_TYPE (event)) {
1319
0
    case GST_EVENT_SEGMENT:
1320
0
    {
1321
0
      GstSegment segment;
1322
1323
0
      GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1324
1325
0
      gst_event_copy_segment (event, &segment);
1326
1327
0
      GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
1328
1329
0
      if (segment.format != GST_FORMAT_TIME) {
1330
0
        GST_DEBUG_OBJECT (encoder, "received non TIME segment");
1331
0
        GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1332
0
        break;
1333
0
      }
1334
1335
0
      if (encoder->priv->time_adjustment != GST_CLOCK_TIME_NONE) {
1336
0
        segment.start += encoder->priv->time_adjustment;
1337
0
        if (GST_CLOCK_TIME_IS_VALID (segment.position)) {
1338
0
          segment.position += encoder->priv->time_adjustment;
1339
0
        }
1340
0
        if (GST_CLOCK_TIME_IS_VALID (segment.stop)) {
1341
0
          segment.stop += encoder->priv->time_adjustment;
1342
0
        }
1343
0
      }
1344
1345
0
      encoder->output_segment = segment;
1346
0
      GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1347
1348
0
      gst_event_unref (event);
1349
0
      event = gst_event_new_segment (&encoder->output_segment);
1350
1351
0
      break;
1352
0
    }
1353
0
    default:
1354
0
      break;
1355
0
  }
1356
1357
0
  return gst_pad_push_event (encoder->srcpad, event);
1358
0
}
1359
1360
static GstEvent *
1361
gst_video_encoder_create_merged_tags_event (GstVideoEncoder * enc)
1362
0
{
1363
0
  GstTagList *merged_tags;
1364
1365
0
  GST_LOG_OBJECT (enc, "upstream : %" GST_PTR_FORMAT, enc->priv->upstream_tags);
1366
0
  GST_LOG_OBJECT (enc, "encoder  : %" GST_PTR_FORMAT, enc->priv->tags);
1367
0
  GST_LOG_OBJECT (enc, "mode     : %d", enc->priv->tags_merge_mode);
1368
1369
0
  merged_tags =
1370
0
      gst_tag_list_merge (enc->priv->upstream_tags, enc->priv->tags,
1371
0
      enc->priv->tags_merge_mode);
1372
1373
0
  GST_DEBUG_OBJECT (enc, "merged   : %" GST_PTR_FORMAT, merged_tags);
1374
1375
0
  if (merged_tags == NULL)
1376
0
    return NULL;
1377
1378
0
  if (gst_tag_list_is_empty (merged_tags)) {
1379
0
    gst_tag_list_unref (merged_tags);
1380
0
    return NULL;
1381
0
  }
1382
1383
0
  return gst_event_new_tag (merged_tags);
1384
0
}
1385
1386
static inline void
1387
gst_video_encoder_check_and_push_tags (GstVideoEncoder * encoder)
1388
0
{
1389
0
  if (encoder->priv->tags_changed) {
1390
0
    GstEvent *tags_event;
1391
1392
0
    tags_event = gst_video_encoder_create_merged_tags_event (encoder);
1393
1394
0
    if (tags_event != NULL)
1395
0
      gst_video_encoder_push_event (encoder, tags_event);
1396
1397
0
    encoder->priv->tags_changed = FALSE;
1398
0
  }
1399
0
}
1400
1401
static gboolean
1402
gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
1403
    GstEvent * event)
1404
0
{
1405
0
  GstVideoEncoderClass *encoder_class;
1406
0
  gboolean ret = FALSE;
1407
1408
0
  encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1409
1410
0
  switch (GST_EVENT_TYPE (event)) {
1411
0
    case GST_EVENT_CAPS:
1412
0
    {
1413
0
      GstCaps *caps;
1414
1415
0
      gst_event_parse_caps (event, &caps);
1416
0
      ret = gst_video_encoder_setcaps (encoder, caps);
1417
1418
0
      gst_event_unref (event);
1419
0
      event = NULL;
1420
0
      break;
1421
0
    }
1422
0
    case GST_EVENT_EOS:
1423
0
    {
1424
0
      GstFlowReturn flow_ret;
1425
1426
0
      GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1427
1428
0
      if (encoder_class->finish) {
1429
0
        flow_ret = encoder_class->finish (encoder);
1430
0
      } else {
1431
0
        flow_ret = GST_FLOW_OK;
1432
0
      }
1433
1434
0
      if (encoder->priv->current_frame_events) {
1435
0
        GList *l;
1436
1437
0
        for (l = g_list_last (encoder->priv->current_frame_events); l;
1438
0
            l = g_list_previous (l)) {
1439
0
          GstEvent *event = GST_EVENT (l->data);
1440
1441
0
          gst_video_encoder_push_event (encoder, event);
1442
0
        }
1443
0
      }
1444
0
      g_list_free (encoder->priv->current_frame_events);
1445
0
      encoder->priv->current_frame_events = NULL;
1446
1447
0
      gst_video_encoder_check_and_push_tags (encoder);
1448
1449
0
      ret = (flow_ret == GST_FLOW_OK);
1450
0
      GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1451
0
      break;
1452
0
    }
1453
0
    case GST_EVENT_SEGMENT:
1454
0
    {
1455
0
      GstSegment segment;
1456
1457
0
      GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1458
1459
0
      gst_event_copy_segment (event, &segment);
1460
1461
0
      GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
1462
1463
0
      if (segment.format != GST_FORMAT_TIME) {
1464
0
        GST_DEBUG_OBJECT (encoder, "received non TIME newsegment");
1465
0
        GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1466
0
        break;
1467
0
      }
1468
1469
0
      encoder->input_segment = segment;
1470
0
      ret = TRUE;
1471
0
      GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1472
0
      break;
1473
0
    }
1474
0
    case GST_EVENT_CUSTOM_DOWNSTREAM:
1475
0
    {
1476
0
      if (gst_video_event_is_force_key_unit (event)) {
1477
0
        GstClockTime running_time;
1478
0
        gboolean all_headers;
1479
0
        guint count;
1480
1481
0
        if (gst_video_event_parse_downstream_force_key_unit (event,
1482
0
                NULL, NULL, &running_time, &all_headers, &count)) {
1483
0
          ForcedKeyUnitEvent *fevt;
1484
1485
0
          GST_OBJECT_LOCK (encoder);
1486
0
          fevt = forced_key_unit_event_new (running_time, all_headers, count);
1487
0
          g_queue_insert_sorted (&encoder->priv->force_key_unit, fevt,
1488
0
              (GCompareDataFunc) forced_key_unit_event_compare, NULL);
1489
0
          GST_OBJECT_UNLOCK (encoder);
1490
1491
0
          GST_DEBUG_OBJECT (encoder,
1492
0
              "force-key-unit event: running-time %" GST_TIME_FORMAT
1493
0
              ", all_headers %d, count %u",
1494
0
              GST_TIME_ARGS (running_time), all_headers, count);
1495
0
        }
1496
0
        gst_event_unref (event);
1497
0
        event = NULL;
1498
0
        ret = TRUE;
1499
0
      }
1500
0
      break;
1501
0
    }
1502
0
    case GST_EVENT_STREAM_START:
1503
0
    {
1504
0
      GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1505
      /* Flush upstream tags after a STREAM_START */
1506
0
      GST_DEBUG_OBJECT (encoder, "STREAM_START, clearing upstream tags");
1507
0
      if (encoder->priv->upstream_tags) {
1508
0
        gst_tag_list_unref (encoder->priv->upstream_tags);
1509
0
        encoder->priv->upstream_tags = NULL;
1510
0
        encoder->priv->tags_changed = TRUE;
1511
0
      }
1512
0
      GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1513
0
      break;
1514
0
    }
1515
0
    case GST_EVENT_TAG:
1516
0
    {
1517
0
      GstTagList *tags;
1518
1519
0
      gst_event_parse_tag (event, &tags);
1520
1521
0
      if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
1522
0
        GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1523
0
        if (encoder->priv->upstream_tags != tags) {
1524
0
          tags = gst_tag_list_copy (tags);
1525
1526
          /* FIXME: make generic based on GST_TAG_FLAG_ENCODED */
1527
0
          gst_tag_list_remove_tag (tags, GST_TAG_CODEC);
1528
0
          gst_tag_list_remove_tag (tags, GST_TAG_AUDIO_CODEC);
1529
0
          gst_tag_list_remove_tag (tags, GST_TAG_VIDEO_CODEC);
1530
0
          gst_tag_list_remove_tag (tags, GST_TAG_SUBTITLE_CODEC);
1531
0
          gst_tag_list_remove_tag (tags, GST_TAG_CONTAINER_FORMAT);
1532
0
          gst_tag_list_remove_tag (tags, GST_TAG_BITRATE);
1533
0
          gst_tag_list_remove_tag (tags, GST_TAG_NOMINAL_BITRATE);
1534
0
          gst_tag_list_remove_tag (tags, GST_TAG_MAXIMUM_BITRATE);
1535
0
          gst_tag_list_remove_tag (tags, GST_TAG_MINIMUM_BITRATE);
1536
0
          gst_tag_list_remove_tag (tags, GST_TAG_ENCODER);
1537
0
          gst_tag_list_remove_tag (tags, GST_TAG_ENCODER_VERSION);
1538
1539
0
          if (encoder->priv->upstream_tags)
1540
0
            gst_tag_list_unref (encoder->priv->upstream_tags);
1541
0
          encoder->priv->upstream_tags = tags;
1542
0
          GST_INFO_OBJECT (encoder, "upstream tags: %" GST_PTR_FORMAT, tags);
1543
0
        }
1544
0
        gst_event_unref (event);
1545
0
        event = gst_video_encoder_create_merged_tags_event (encoder);
1546
0
        GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1547
0
        if (!event)
1548
0
          ret = TRUE;
1549
0
      }
1550
0
      break;
1551
0
    }
1552
0
    case GST_EVENT_FLUSH_STOP:{
1553
0
      GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1554
0
      gst_video_encoder_flush (encoder);
1555
0
      gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
1556
0
      gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
1557
0
      gst_video_encoder_reset (encoder, FALSE);
1558
0
      GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1559
0
      break;
1560
0
    }
1561
0
    default:
1562
0
      break;
1563
0
  }
1564
1565
  /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
1566
   * For EOS this is required because no buffer or serialized event
1567
   * will come after EOS and nothing could trigger another
1568
   * _finish_frame() call.   *
1569
   * If the subclass handles sending of EOS manually it can simply
1570
   * not chain up to the parent class' event handler
1571
   *
1572
   * For FLUSH_STOP this is required because it is expected
1573
   * to be forwarded immediately and no buffers are queued anyway.
1574
   */
1575
0
  if (event) {
1576
0
    if (!GST_EVENT_IS_SERIALIZED (event)
1577
0
        || GST_EVENT_TYPE (event) == GST_EVENT_EOS
1578
0
        || GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_STOP) {
1579
0
      ret = gst_video_encoder_push_event (encoder, event);
1580
0
    } else {
1581
0
      GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1582
0
      encoder->priv->current_frame_events =
1583
0
          g_list_prepend (encoder->priv->current_frame_events, event);
1584
0
      GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1585
0
      ret = TRUE;
1586
0
    }
1587
0
  }
1588
1589
0
  return ret;
1590
0
}
1591
1592
static gboolean
1593
gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
1594
    GstEvent * event)
1595
0
{
1596
0
  GstVideoEncoder *enc;
1597
0
  GstVideoEncoderClass *klass;
1598
0
  gboolean ret = TRUE;
1599
1600
0
  enc = GST_VIDEO_ENCODER (parent);
1601
0
  klass = GST_VIDEO_ENCODER_GET_CLASS (enc);
1602
1603
0
  GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1604
0
      GST_EVENT_TYPE_NAME (event));
1605
1606
0
  if (klass->sink_event)
1607
0
    ret = klass->sink_event (enc, event);
1608
1609
0
  return ret;
1610
0
}
1611
1612
static gboolean
1613
gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
1614
    GstEvent * event)
1615
0
{
1616
0
  gboolean ret = FALSE;
1617
0
  GstVideoEncoderPrivate *priv = encoder->priv;
1618
1619
0
  switch (GST_EVENT_TYPE (event)) {
1620
0
    case GST_EVENT_CUSTOM_UPSTREAM:
1621
0
    {
1622
0
      if (gst_video_event_is_force_key_unit (event)) {
1623
0
        GstClockTime running_time;
1624
0
        gboolean all_headers;
1625
0
        guint count;
1626
1627
0
        if (gst_video_event_parse_upstream_force_key_unit (event,
1628
0
                &running_time, &all_headers, &count)) {
1629
0
          ForcedKeyUnitEvent *fevt;
1630
1631
0
          GST_OBJECT_LOCK (encoder);
1632
0
          fevt = forced_key_unit_event_new (running_time, all_headers, count);
1633
0
          g_queue_insert_sorted (&encoder->priv->force_key_unit, fevt,
1634
0
              (GCompareDataFunc) forced_key_unit_event_compare, NULL);
1635
0
          GST_OBJECT_UNLOCK (encoder);
1636
1637
0
          GST_DEBUG_OBJECT (encoder,
1638
0
              "force-key-unit event: running-time %" GST_TIME_FORMAT
1639
0
              ", all_headers %d, count %u",
1640
0
              GST_TIME_ARGS (running_time), all_headers, count);
1641
0
        }
1642
0
        gst_event_unref (event);
1643
0
        event = NULL;
1644
0
        ret = TRUE;
1645
0
      }
1646
0
      break;
1647
0
    }
1648
0
    case GST_EVENT_QOS:
1649
0
    {
1650
0
      GstQOSType type;
1651
0
      gdouble proportion;
1652
0
      GstClockTimeDiff diff;
1653
0
      GstClockTime timestamp;
1654
1655
0
      if (!g_atomic_int_get (&priv->qos_enabled))
1656
0
        break;
1657
1658
0
      gst_event_parse_qos (event, &type, &proportion, &diff, &timestamp);
1659
1660
0
      GST_OBJECT_LOCK (encoder);
1661
0
      priv->proportion = proportion;
1662
0
      if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (timestamp))) {
1663
0
        if (G_UNLIKELY (diff > 0)) {
1664
0
          priv->earliest_time =
1665
0
              timestamp + MIN (2 * diff, GST_SECOND) + priv->qos_frame_duration;
1666
0
        } else {
1667
0
          priv->earliest_time = timestamp + diff;
1668
0
        }
1669
0
      } else {
1670
0
        priv->earliest_time = GST_CLOCK_TIME_NONE;
1671
0
      }
1672
0
      GST_OBJECT_UNLOCK (encoder);
1673
1674
0
      GST_DEBUG_OBJECT (encoder,
1675
0
          "got QoS %" GST_TIME_FORMAT ", %" GST_STIME_FORMAT ", %g",
1676
0
          GST_TIME_ARGS (timestamp), GST_STIME_ARGS (diff), proportion);
1677
1678
0
      ret = gst_pad_push_event (encoder->sinkpad, event);
1679
0
      event = NULL;
1680
0
      break;
1681
0
    }
1682
0
    default:
1683
0
      break;
1684
0
  }
1685
1686
0
  if (event)
1687
0
    ret =
1688
0
        gst_pad_event_default (encoder->srcpad, GST_OBJECT_CAST (encoder),
1689
0
        event);
1690
1691
0
  return ret;
1692
0
}
1693
1694
static gboolean
1695
gst_video_encoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1696
0
{
1697
0
  GstVideoEncoder *encoder;
1698
0
  GstVideoEncoderClass *klass;
1699
0
  gboolean ret = FALSE;
1700
1701
0
  encoder = GST_VIDEO_ENCODER (parent);
1702
0
  klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1703
1704
0
  GST_LOG_OBJECT (encoder, "handling event: %" GST_PTR_FORMAT, event);
1705
1706
0
  if (klass->src_event)
1707
0
    ret = klass->src_event (encoder, event);
1708
1709
0
  return ret;
1710
0
}
1711
1712
static gboolean
1713
gst_video_encoder_src_query_default (GstVideoEncoder * enc, GstQuery * query)
1714
0
{
1715
0
  GstPad *pad = GST_VIDEO_ENCODER_SRC_PAD (enc);
1716
0
  GstVideoEncoderPrivate *priv;
1717
0
  gboolean res;
1718
1719
0
  priv = enc->priv;
1720
1721
0
  GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1722
1723
0
  switch (GST_QUERY_TYPE (query)) {
1724
0
    case GST_QUERY_CONVERT:
1725
0
    {
1726
0
      GstFormat src_fmt, dest_fmt;
1727
0
      gint64 src_val, dest_val;
1728
1729
0
      gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1730
0
      GST_OBJECT_LOCK (enc);
1731
0
      res =
1732
0
          __gst_video_encoded_video_convert (priv->bytes, priv->time, src_fmt,
1733
0
          src_val, &dest_fmt, &dest_val);
1734
0
      GST_OBJECT_UNLOCK (enc);
1735
0
      if (!res)
1736
0
        goto error;
1737
0
      gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1738
0
      break;
1739
0
    }
1740
0
    case GST_QUERY_LATENCY:
1741
0
    {
1742
0
      gboolean live;
1743
0
      GstClockTime min_latency, max_latency;
1744
1745
0
      res = gst_pad_peer_query (enc->sinkpad, query);
1746
0
      if (res) {
1747
0
        gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1748
0
        GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1749
0
            GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1750
0
            GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1751
1752
0
        GST_OBJECT_LOCK (enc);
1753
0
        min_latency += priv->min_latency;
1754
0
        if (max_latency == GST_CLOCK_TIME_NONE
1755
0
            || enc->priv->max_latency == GST_CLOCK_TIME_NONE)
1756
0
          max_latency = GST_CLOCK_TIME_NONE;
1757
0
        else
1758
0
          max_latency += enc->priv->max_latency;
1759
0
        GST_OBJECT_UNLOCK (enc);
1760
1761
0
        gst_query_set_latency (query, live, min_latency, max_latency);
1762
0
      }
1763
0
    }
1764
0
      break;
1765
0
    default:
1766
0
      res = gst_pad_query_default (pad, GST_OBJECT (enc), query);
1767
0
  }
1768
0
  return res;
1769
1770
0
error:
1771
0
  GST_DEBUG_OBJECT (enc, "query failed");
1772
0
  return res;
1773
0
}
1774
1775
static gboolean
1776
gst_video_encoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1777
0
{
1778
0
  GstVideoEncoder *encoder;
1779
0
  GstVideoEncoderClass *encoder_class;
1780
0
  gboolean ret = FALSE;
1781
1782
0
  encoder = GST_VIDEO_ENCODER (parent);
1783
0
  encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1784
1785
0
  GST_DEBUG_OBJECT (encoder, "received query %d, %s", GST_QUERY_TYPE (query),
1786
0
      GST_QUERY_TYPE_NAME (query));
1787
1788
0
  if (encoder_class->src_query)
1789
0
    ret = encoder_class->src_query (encoder, query);
1790
1791
0
  return ret;
1792
0
}
1793
1794
static GstVideoCodecFrame *
1795
gst_video_encoder_new_frame (GstVideoEncoder * encoder, GstBuffer * buf,
1796
    GstClockTime pts, GstClockTime dts, GstClockTime duration)
1797
0
{
1798
0
  GstVideoEncoderPrivate *priv = encoder->priv;
1799
0
  GstVideoCodecFrame *frame;
1800
1801
0
  frame = g_new0 (GstVideoCodecFrame, 1);
1802
1803
0
  g_atomic_ref_count_init ((gatomicrefcount *) & frame->ref_count);
1804
1805
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1806
0
  frame->system_frame_number = priv->system_frame_number;
1807
0
  priv->system_frame_number++;
1808
1809
0
  frame->presentation_frame_number = priv->presentation_frame_number;
1810
0
  priv->presentation_frame_number++;
1811
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1812
1813
0
  frame->events = priv->current_frame_events;
1814
0
  priv->current_frame_events = NULL;
1815
0
  frame->input_buffer = buf;
1816
0
  frame->pts = pts;
1817
0
  frame->dts = dts;
1818
0
  frame->duration = duration;
1819
0
  frame->abidata.ABI.ts = pts;
1820
1821
0
  return frame;
1822
0
}
1823
1824
1825
static GstFlowReturn
1826
gst_video_encoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
1827
0
{
1828
0
  GstVideoEncoder *encoder;
1829
0
  GstVideoEncoderPrivate *priv;
1830
0
  GstVideoEncoderClass *klass;
1831
0
  GstVideoCodecFrame *frame;
1832
0
  GstClockTime pts, duration;
1833
0
  GstFlowReturn ret = GST_FLOW_OK;
1834
0
  guint64 start, stop, cstart, cstop;
1835
0
  guint64 cstart_adjusted;
1836
1837
0
  encoder = GST_VIDEO_ENCODER (parent);
1838
0
  priv = encoder->priv;
1839
0
  klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1840
1841
0
  g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
1842
1843
0
  if (!encoder->priv->input_state)
1844
0
    goto not_negotiated;
1845
1846
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1847
1848
0
  pts = GST_BUFFER_PTS (buf);
1849
0
  duration = GST_BUFFER_DURATION (buf);
1850
1851
0
  GST_LOG_OBJECT (encoder,
1852
0
      "received buffer of size %" G_GSIZE_FORMAT " with PTS %" GST_TIME_FORMAT
1853
0
      ", DTS %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
1854
0
      gst_buffer_get_size (buf), GST_TIME_ARGS (pts),
1855
0
      GST_TIME_ARGS (GST_BUFFER_DTS (buf)), GST_TIME_ARGS (duration));
1856
1857
0
  start = pts;
1858
0
  if (GST_CLOCK_TIME_IS_VALID (duration))
1859
0
    stop = start + duration;
1860
0
  else
1861
0
    stop = GST_CLOCK_TIME_NONE;
1862
1863
  /* Drop buffers outside of segment */
1864
0
  if (!gst_segment_clip (&encoder->input_segment,
1865
0
          GST_FORMAT_TIME, start, stop, &cstart, &cstop)) {
1866
0
    GST_DEBUG_OBJECT (encoder, "clipping to segment dropped frame");
1867
0
    gst_buffer_unref (buf);
1868
0
    goto done;
1869
0
  }
1870
1871
0
  if (GST_CLOCK_TIME_IS_VALID (cstop))
1872
0
    duration = cstop - cstart;
1873
0
  else
1874
0
    duration = GST_CLOCK_TIME_NONE;
1875
1876
0
  if (priv->min_pts != GST_CLOCK_TIME_NONE
1877
0
      && priv->time_adjustment == GST_CLOCK_TIME_NONE) {
1878
0
    if (cstart < priv->min_pts) {
1879
0
      priv->time_adjustment = priv->min_pts - cstart;
1880
0
    }
1881
0
  }
1882
1883
0
  if (priv->time_adjustment != GST_CLOCK_TIME_NONE) {
1884
0
    cstart_adjusted = cstart + priv->time_adjustment;
1885
0
  } else {
1886
0
    cstart_adjusted = cstart;
1887
0
  }
1888
1889
  /* incoming DTS is not really relevant and does not make sense anyway,
1890
   * so pass along _NONE and maybe come up with something better later on */
1891
0
  frame = gst_video_encoder_new_frame (encoder, buf, cstart_adjusted,
1892
0
      GST_CLOCK_TIME_NONE, duration);
1893
1894
0
  GST_OBJECT_LOCK (encoder);
1895
0
  if (priv->force_key_unit.head) {
1896
0
    GList *l;
1897
0
    GstClockTime running_time;
1898
0
    gboolean throttled, have_fevt = FALSE, have_pending_none_fevt = FALSE;
1899
0
    GQueue matching_fevt = G_QUEUE_INIT;
1900
1901
0
    running_time =
1902
0
        gst_segment_to_running_time (&encoder->input_segment, GST_FORMAT_TIME,
1903
0
        cstart);
1904
1905
0
    throttled = (priv->min_force_key_unit_interval != 0 &&
1906
0
        priv->min_force_key_unit_interval != GST_CLOCK_TIME_NONE &&
1907
0
        ((priv->last_force_key_unit_request != GST_CLOCK_TIME_NONE &&
1908
0
                priv->last_force_key_unit_request +
1909
0
                priv->min_force_key_unit_interval > running_time)
1910
0
            || (priv->last_key_unit != GST_CLOCK_TIME_NONE
1911
0
                && priv->last_key_unit + priv->min_force_key_unit_interval >
1912
0
                running_time)));
1913
1914
0
    for (l = priv->force_key_unit.head; l && (!throttled || !have_fevt);
1915
0
        l = l->next) {
1916
0
      ForcedKeyUnitEvent *fevt = l->data;
1917
1918
      /* Skip pending keyunits */
1919
0
      if (fevt->pending) {
1920
0
        if (fevt->running_time == GST_CLOCK_TIME_NONE)
1921
0
          have_pending_none_fevt = TRUE;
1922
0
        continue;
1923
0
      }
1924
1925
      /* Simple case, keyunit ASAP */
1926
0
      if (fevt->running_time == GST_CLOCK_TIME_NONE) {
1927
0
        have_fevt = TRUE;
1928
0
        if (!throttled)
1929
0
          g_queue_push_tail (&matching_fevt, fevt);
1930
0
        continue;
1931
0
      }
1932
1933
      /* Event for before this frame */
1934
0
      if (fevt->running_time <= running_time) {
1935
0
        have_fevt = TRUE;
1936
0
        if (!throttled)
1937
0
          g_queue_push_tail (&matching_fevt, fevt);
1938
0
        continue;
1939
0
      }
1940
1941
      /* Otherwise all following events are in the future */
1942
0
      break;
1943
0
    }
1944
1945
0
    if (throttled && have_fevt) {
1946
0
      GstClockTime last_time;
1947
1948
0
      if (priv->last_force_key_unit_request != GST_CLOCK_TIME_NONE &&
1949
0
          priv->last_force_key_unit_request +
1950
0
          priv->min_force_key_unit_interval > running_time) {
1951
0
        last_time = priv->last_force_key_unit_request;
1952
0
      } else {
1953
0
        last_time = priv->last_key_unit;
1954
0
      }
1955
1956
0
      GST_DEBUG_OBJECT (encoder,
1957
0
          "Not requesting a new key unit yet due to throttling (%"
1958
0
          GST_TIME_FORMAT " + %" GST_TIME_FORMAT " > %" GST_TIME_FORMAT,
1959
0
          GST_TIME_ARGS (last_time),
1960
0
          GST_TIME_ARGS (priv->min_force_key_unit_interval),
1961
0
          GST_TIME_ARGS (running_time));
1962
0
      g_queue_clear (&matching_fevt);
1963
0
    }
1964
1965
0
    if (matching_fevt.length > 0) {
1966
0
      ForcedKeyUnitEvent *fevt;
1967
0
      gboolean all_headers = FALSE;
1968
0
      gboolean force_keyunit = FALSE;
1969
1970
0
      while ((fevt = g_queue_pop_head (&matching_fevt))) {
1971
0
        fevt->pending = TRUE;
1972
1973
0
        if ((fevt->running_time == GST_CLOCK_TIME_NONE
1974
0
                && have_pending_none_fevt)
1975
0
            || (priv->last_force_key_unit_request != GST_CLOCK_TIME_NONE
1976
0
                && fevt->running_time != GST_CLOCK_TIME_NONE
1977
0
                && fevt->running_time <= priv->last_force_key_unit_request) ||
1978
0
            (priv->last_key_unit != GST_CLOCK_TIME_NONE
1979
0
                && fevt->running_time != GST_CLOCK_TIME_NONE
1980
0
                && fevt->running_time <= priv->last_key_unit)) {
1981
0
          GST_DEBUG_OBJECT (encoder,
1982
0
              "Not requesting another key unit at running time %"
1983
0
              GST_TIME_FORMAT, GST_TIME_ARGS (fevt->running_time));
1984
0
        } else {
1985
0
          force_keyunit = TRUE;
1986
0
          fevt->frame_id = frame->system_frame_number;
1987
0
          if (fevt->all_headers)
1988
0
            all_headers = TRUE;
1989
0
        }
1990
0
      }
1991
1992
0
      if (force_keyunit) {
1993
0
        GST_DEBUG_OBJECT (encoder,
1994
0
            "Forcing a key unit at running time %" GST_TIME_FORMAT,
1995
0
            GST_TIME_ARGS (running_time));
1996
1997
0
        GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME (frame);
1998
0
        if (all_headers)
1999
0
          GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME_HEADERS (frame);
2000
0
        priv->last_force_key_unit_request = running_time;
2001
0
      }
2002
0
    }
2003
0
  }
2004
0
  GST_OBJECT_UNLOCK (encoder);
2005
2006
0
  g_queue_push_tail (&priv->frames, gst_video_codec_frame_ref (frame));
2007
2008
  /* new data, more finish needed */
2009
0
  priv->drained = FALSE;
2010
2011
0
  GST_LOG_OBJECT (encoder, "passing frame pfn %d to subclass",
2012
0
      frame->presentation_frame_number);
2013
2014
0
  frame->deadline =
2015
0
      gst_segment_to_running_time (&encoder->input_segment, GST_FORMAT_TIME,
2016
0
      cstart);
2017
2018
0
  ret = klass->handle_frame (encoder, frame);
2019
2020
0
done:
2021
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2022
2023
0
  return ret;
2024
2025
  /* ERRORS */
2026
0
not_negotiated:
2027
0
  {
2028
0
    GST_ELEMENT_ERROR (encoder, CORE, NEGOTIATION, (NULL),
2029
0
        ("encoder not initialized"));
2030
0
    gst_buffer_unref (buf);
2031
0
    return GST_FLOW_NOT_NEGOTIATED;
2032
0
  }
2033
0
}
2034
2035
static GstStateChangeReturn
2036
gst_video_encoder_change_state (GstElement * element, GstStateChange transition)
2037
0
{
2038
0
  GstVideoEncoder *encoder;
2039
0
  GstVideoEncoderClass *encoder_class;
2040
0
  GstStateChangeReturn ret;
2041
2042
0
  encoder = GST_VIDEO_ENCODER (element);
2043
0
  encoder_class = GST_VIDEO_ENCODER_GET_CLASS (element);
2044
2045
0
  switch (transition) {
2046
0
    case GST_STATE_CHANGE_NULL_TO_READY:
2047
      /* open device/library if needed */
2048
0
      if (encoder_class->open && !encoder_class->open (encoder))
2049
0
        goto open_failed;
2050
0
      break;
2051
0
    case GST_STATE_CHANGE_READY_TO_PAUSED:
2052
0
      GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2053
0
      gst_video_encoder_reset (encoder, TRUE);
2054
0
      GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2055
2056
      /* Initialize device/library if needed */
2057
0
      if (encoder_class->start && !encoder_class->start (encoder))
2058
0
        goto start_failed;
2059
0
      break;
2060
0
    default:
2061
0
      break;
2062
0
  }
2063
2064
0
  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2065
2066
0
  switch (transition) {
2067
0
    case GST_STATE_CHANGE_PAUSED_TO_READY:{
2068
0
      gboolean stopped = TRUE;
2069
2070
0
      if (encoder_class->stop)
2071
0
        stopped = encoder_class->stop (encoder);
2072
2073
0
      GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2074
0
      gst_video_encoder_reset (encoder, TRUE);
2075
0
      GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2076
2077
0
      if (!stopped)
2078
0
        goto stop_failed;
2079
0
      break;
2080
0
    }
2081
0
    case GST_STATE_CHANGE_READY_TO_NULL:
2082
      /* close device/library if needed */
2083
0
      if (encoder_class->close && !encoder_class->close (encoder))
2084
0
        goto close_failed;
2085
0
      break;
2086
0
    default:
2087
0
      break;
2088
0
  }
2089
2090
0
  return ret;
2091
2092
  /* Errors */
2093
2094
0
open_failed:
2095
0
  {
2096
0
    GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
2097
0
        ("Failed to open encoder"));
2098
0
    return GST_STATE_CHANGE_FAILURE;
2099
0
  }
2100
2101
0
start_failed:
2102
0
  {
2103
0
    GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
2104
0
        ("Failed to start encoder"));
2105
0
    return GST_STATE_CHANGE_FAILURE;
2106
0
  }
2107
2108
0
stop_failed:
2109
0
  {
2110
0
    GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
2111
0
        ("Failed to stop encoder"));
2112
0
    return GST_STATE_CHANGE_FAILURE;
2113
0
  }
2114
2115
0
close_failed:
2116
0
  {
2117
0
    GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
2118
0
        ("Failed to close encoder"));
2119
0
    return GST_STATE_CHANGE_FAILURE;
2120
0
  }
2121
0
}
2122
2123
static gboolean
2124
gst_video_encoder_negotiate_default (GstVideoEncoder * encoder)
2125
0
{
2126
0
  GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
2127
0
  gboolean ret = TRUE;
2128
0
  GstVideoCodecState *state = encoder->priv->output_state;
2129
0
  GstVideoInfo *info = &state->info;
2130
0
  GstVideoCodecFrame *frame;
2131
0
  GstCaps *prevcaps;
2132
0
  gchar *colorimetry;
2133
2134
0
  g_return_val_if_fail (state->caps != NULL, FALSE);
2135
2136
0
  if (encoder->priv->output_state_changed) {
2137
0
    GstStructure *out_struct;
2138
2139
0
    state->caps = gst_caps_make_writable (state->caps);
2140
2141
    /* Fill caps */
2142
0
    gst_caps_set_simple (state->caps, "width", G_TYPE_INT, info->width,
2143
0
        "height", G_TYPE_INT, info->height,
2144
0
        "pixel-aspect-ratio", GST_TYPE_FRACTION,
2145
0
        info->par_n, info->par_d, NULL);
2146
0
    if (info->flags & GST_VIDEO_FLAG_VARIABLE_FPS && info->fps_n != 0) {
2147
      /* variable fps with a max-framerate */
2148
0
      gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION, 0, 1,
2149
0
          "max-framerate", GST_TYPE_FRACTION, info->fps_n, info->fps_d, NULL);
2150
0
    } else {
2151
      /* no variable fps or no max-framerate */
2152
0
      gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION,
2153
0
          info->fps_n, info->fps_d, NULL);
2154
0
    }
2155
0
    if (state->codec_data)
2156
0
      gst_caps_set_simple (state->caps, "codec_data", GST_TYPE_BUFFER,
2157
0
          state->codec_data, NULL);
2158
2159
0
    gst_caps_set_simple (state->caps, "interlace-mode", G_TYPE_STRING,
2160
0
        gst_video_interlace_mode_to_string (info->interlace_mode), NULL);
2161
0
    if ((info->interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED ||
2162
0
            info->interlace_mode == GST_VIDEO_INTERLACE_MODE_FIELDS ||
2163
0
            info->interlace_mode == GST_VIDEO_INTERLACE_MODE_ALTERNATE) &&
2164
0
        GST_VIDEO_INFO_FIELD_ORDER (info) != GST_VIDEO_FIELD_ORDER_UNKNOWN)
2165
0
      gst_caps_set_simple (state->caps, "field-order", G_TYPE_STRING,
2166
0
          gst_video_field_order_to_string (GST_VIDEO_INFO_FIELD_ORDER (info)),
2167
0
          NULL);
2168
2169
0
    colorimetry = gst_video_colorimetry_to_string (&info->colorimetry);
2170
0
    if (colorimetry)
2171
0
      gst_caps_set_simple (state->caps, "colorimetry", G_TYPE_STRING,
2172
0
          colorimetry, NULL);
2173
0
    g_free (colorimetry);
2174
2175
0
    if (info->chroma_site != GST_VIDEO_CHROMA_SITE_UNKNOWN) {
2176
0
      gchar *chroma_site = gst_video_chroma_site_to_string (info->chroma_site);
2177
2178
0
      if (!chroma_site) {
2179
0
        GST_WARNING ("Couldn't convert chroma-site 0x%x to string",
2180
0
            info->chroma_site);
2181
0
      } else {
2182
0
        gst_caps_set_simple (state->caps,
2183
0
            "chroma-site", G_TYPE_STRING, chroma_site, NULL);
2184
0
        g_free (chroma_site);
2185
0
      }
2186
0
    }
2187
2188
0
    if (GST_VIDEO_INFO_MULTIVIEW_MODE (info) != GST_VIDEO_MULTIVIEW_MODE_NONE) {
2189
0
      const gchar *caps_mview_mode =
2190
0
          gst_video_multiview_mode_to_caps_string (GST_VIDEO_INFO_MULTIVIEW_MODE
2191
0
          (info));
2192
2193
0
      gst_caps_set_simple (state->caps, "multiview-mode", G_TYPE_STRING,
2194
0
          caps_mview_mode, "multiview-flags", GST_TYPE_VIDEO_MULTIVIEW_FLAGSET,
2195
0
          GST_VIDEO_INFO_MULTIVIEW_FLAGS (info), GST_FLAG_SET_MASK_EXACT, NULL);
2196
0
    }
2197
2198
0
    out_struct = gst_caps_get_structure (state->caps, 0);
2199
2200
    /* forward upstream mastering display info and content light level
2201
     * if subclass didn't set */
2202
0
    if (state->mastering_display_info &&
2203
0
        !gst_structure_has_field (out_struct, "mastering-display-info")) {
2204
0
      gst_video_mastering_display_info_add_to_caps
2205
0
          (state->mastering_display_info, state->caps);
2206
0
    }
2207
2208
0
    if (state->content_light_level &&
2209
0
        !gst_structure_has_field (out_struct, "content-light-level")) {
2210
0
      gst_video_content_light_level_add_to_caps (state->content_light_level,
2211
0
          state->caps);
2212
0
    }
2213
2214
0
    encoder->priv->output_state_changed = FALSE;
2215
0
  }
2216
2217
0
  if (state->allocation_caps == NULL)
2218
0
    state->allocation_caps = gst_caps_ref (state->caps);
2219
2220
  /* Push all pending pre-caps events of the oldest frame before
2221
   * setting caps */
2222
0
  frame = encoder->priv->frames.head ? encoder->priv->frames.head->data : NULL;
2223
0
  if (frame || encoder->priv->current_frame_events) {
2224
0
    GList **events, *l;
2225
2226
0
    if (frame) {
2227
0
      events = &frame->events;
2228
0
    } else {
2229
0
      events = &encoder->priv->current_frame_events;
2230
0
    }
2231
2232
0
    for (l = g_list_last (*events); l;) {
2233
0
      GstEvent *event = GST_EVENT (l->data);
2234
0
      GList *tmp;
2235
2236
0
      if (GST_EVENT_TYPE (event) < GST_EVENT_CAPS) {
2237
0
        gst_video_encoder_push_event (encoder, event);
2238
0
        tmp = l;
2239
0
        l = l->prev;
2240
0
        *events = g_list_delete_link (*events, tmp);
2241
0
      } else {
2242
0
        l = l->prev;
2243
0
      }
2244
0
    }
2245
0
  }
2246
2247
0
  prevcaps = gst_pad_get_current_caps (encoder->srcpad);
2248
0
  if (!prevcaps || !gst_caps_is_equal (prevcaps, state->caps))
2249
0
    ret = gst_pad_set_caps (encoder->srcpad, state->caps);
2250
0
  else
2251
0
    ret = TRUE;
2252
0
  if (prevcaps)
2253
0
    gst_caps_unref (prevcaps);
2254
2255
0
  if (ret && klass->prepare_allocator) {
2256
0
    ret = klass->prepare_allocator (encoder, state->caps);
2257
0
  }
2258
2259
0
  return ret;
2260
0
}
2261
2262
static gboolean
2263
gst_video_encoder_default_prepare_allocator (GstVideoEncoder * encoder,
2264
    GstCaps * caps)
2265
0
{
2266
0
  GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
2267
0
  gboolean ret = TRUE;
2268
0
  GstVideoCodecState *state = encoder->priv->output_state;
2269
0
  GstQuery *query;
2270
0
  GstAllocator *allocator;
2271
0
  GstAllocationParams params;
2272
2273
0
  GST_DEBUG_OBJECT (encoder, "doing allocation query");
2274
2275
0
  query = gst_query_new_allocation (state->allocation_caps, TRUE);
2276
0
  if (!gst_pad_peer_query (encoder->srcpad, query)) {
2277
0
    GST_DEBUG_OBJECT (encoder, "didn't get downstream ALLOCATION hints");
2278
0
  }
2279
2280
0
  g_assert (klass->decide_allocation != NULL);
2281
0
  ret = klass->decide_allocation (encoder, query);
2282
2283
0
  GST_DEBUG_OBJECT (encoder, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, ret,
2284
0
      query);
2285
2286
0
  if (!ret)
2287
0
    goto no_decide_allocation;
2288
2289
  /* we got configuration from our peer or the decide_allocation method,
2290
   * parse them */
2291
0
  if (gst_query_get_n_allocation_params (query) > 0) {
2292
0
    gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
2293
0
  } else {
2294
0
    allocator = NULL;
2295
0
    gst_allocation_params_init (&params);
2296
0
  }
2297
2298
0
  gst_video_encoder_set_allocator (encoder, allocator, &params);
2299
2300
0
done:
2301
0
  if (query)
2302
0
    gst_query_unref (query);
2303
2304
0
  return ret;
2305
2306
  /* Errors */
2307
0
no_decide_allocation:
2308
0
  {
2309
0
    GST_WARNING_OBJECT (encoder, "Subclass failed to decide allocation");
2310
0
    goto done;
2311
0
  }
2312
0
}
2313
2314
/**
2315
 * gst_video_encoder_set_allocator:
2316
 * @encoder: a #GstVideoEncoder
2317
 * @allocator: (transfer full) (nullable): the #GstAllocator
2318
 * @params: (transfer none) (nullable): the #GstAllocationParams of @allocator
2319
 *
2320
 * Allows #GstVideoEncoder sub-classes to set the memory @allocator and
2321
 * its @params.
2322
 *
2323
 * Since: 1.30
2324
 */
2325
void
2326
gst_video_encoder_set_allocator (GstVideoEncoder * encoder,
2327
    GstAllocator * allocator, const GstAllocationParams * params)
2328
0
{
2329
0
  if (encoder->priv->allocator)
2330
0
    gst_object_unref (encoder->priv->allocator);
2331
0
  encoder->priv->allocator = allocator;
2332
0
  encoder->priv->params = *params;
2333
0
}
2334
2335
static gboolean
2336
gst_video_encoder_negotiate_unlocked (GstVideoEncoder * encoder)
2337
0
{
2338
0
  GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
2339
0
  gboolean ret = TRUE;
2340
2341
0
  if (G_LIKELY (klass->negotiate))
2342
0
    ret = klass->negotiate (encoder);
2343
2344
0
  return ret;
2345
0
}
2346
2347
/**
2348
 * gst_video_encoder_negotiate:
2349
 * @encoder: a #GstVideoEncoder
2350
 *
2351
 * Negotiate with downstream elements to currently configured #GstVideoCodecState.
2352
 * Unmark GST_PAD_FLAG_NEED_RECONFIGURE in any case. But mark it again if
2353
 * negotiate fails.
2354
 *
2355
 * Returns: %TRUE if the negotiation succeeded, else %FALSE.
2356
 */
2357
gboolean
2358
gst_video_encoder_negotiate (GstVideoEncoder * encoder)
2359
0
{
2360
0
  GstVideoEncoderClass *klass;
2361
0
  gboolean ret = TRUE;
2362
2363
0
  g_return_val_if_fail (GST_IS_VIDEO_ENCODER (encoder), FALSE);
2364
0
  g_return_val_if_fail (encoder->priv->output_state, FALSE);
2365
2366
0
  klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
2367
2368
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2369
0
  gst_pad_check_reconfigure (encoder->srcpad);
2370
0
  if (klass->negotiate) {
2371
0
    ret = klass->negotiate (encoder);
2372
0
    if (!ret)
2373
0
      gst_pad_mark_reconfigure (encoder->srcpad);
2374
0
  }
2375
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2376
2377
0
  return ret;
2378
0
}
2379
2380
/**
2381
 * gst_video_encoder_allocate_output_buffer:
2382
 * @encoder: a #GstVideoEncoder
2383
 * @size: size of the buffer
2384
 *
2385
 * Helper function that allocates a buffer to hold an encoded video frame
2386
 * for @encoder's current #GstVideoCodecState.
2387
 *
2388
 * Returns: (transfer full): allocated buffer
2389
 */
2390
GstBuffer *
2391
gst_video_encoder_allocate_output_buffer (GstVideoEncoder * encoder, gsize size)
2392
0
{
2393
0
  GstBuffer *buffer;
2394
0
  gboolean needs_reconfigure = FALSE;
2395
2396
0
  g_return_val_if_fail (size > 0, NULL);
2397
2398
0
  GST_DEBUG ("alloc src buffer");
2399
2400
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2401
0
  needs_reconfigure = gst_pad_check_reconfigure (encoder->srcpad);
2402
0
  if (G_UNLIKELY (encoder->priv->output_state_changed
2403
0
          || (encoder->priv->output_state && needs_reconfigure))) {
2404
0
    if (!gst_video_encoder_negotiate_unlocked (encoder)) {
2405
0
      GST_DEBUG_OBJECT (encoder, "Failed to negotiate, fallback allocation");
2406
0
      gst_pad_mark_reconfigure (encoder->srcpad);
2407
0
      goto fallback;
2408
0
    }
2409
0
  }
2410
2411
0
  buffer =
2412
0
      gst_buffer_new_allocate (encoder->priv->allocator, size,
2413
0
      &encoder->priv->params);
2414
0
  if (!buffer) {
2415
0
    GST_INFO_OBJECT (encoder, "couldn't allocate output buffer");
2416
0
    goto fallback;
2417
0
  }
2418
2419
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2420
2421
0
  return buffer;
2422
2423
0
fallback:
2424
0
  buffer = gst_buffer_new_allocate (NULL, size, NULL);
2425
2426
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2427
2428
0
  return buffer;
2429
0
}
2430
2431
/**
2432
 * gst_video_encoder_allocate_output_frame:
2433
 * @encoder: a #GstVideoEncoder
2434
 * @frame: a #GstVideoCodecFrame
2435
 * @size: size of the buffer
2436
 *
2437
 * Helper function that allocates a buffer to hold an encoded video frame for @encoder's
2438
 * current #GstVideoCodecState.  Subclass should already have configured video
2439
 * state and set src pad caps.
2440
 *
2441
 * The buffer allocated here is owned by the frame and you should only
2442
 * keep references to the frame, not the buffer.
2443
 *
2444
 * Returns: %GST_FLOW_OK if an output buffer could be allocated
2445
 */
2446
GstFlowReturn
2447
gst_video_encoder_allocate_output_frame (GstVideoEncoder *
2448
    encoder, GstVideoCodecFrame * frame, gsize size)
2449
0
{
2450
0
  gboolean needs_reconfigure = FALSE;
2451
2452
0
  g_return_val_if_fail (frame->output_buffer == NULL, GST_FLOW_ERROR);
2453
2454
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2455
0
  needs_reconfigure = gst_pad_check_reconfigure (encoder->srcpad);
2456
0
  if (G_UNLIKELY (encoder->priv->output_state_changed
2457
0
          || (encoder->priv->output_state && needs_reconfigure))) {
2458
0
    if (!gst_video_encoder_negotiate_unlocked (encoder)) {
2459
0
      GST_DEBUG_OBJECT (encoder, "Failed to negotiate, fallback allocation");
2460
0
      gst_pad_mark_reconfigure (encoder->srcpad);
2461
0
    }
2462
0
  }
2463
2464
0
  GST_LOG_OBJECT (encoder, "alloc buffer size %" G_GSIZE_FORMAT, size);
2465
2466
0
  frame->output_buffer =
2467
0
      gst_buffer_new_allocate (encoder->priv->allocator, size,
2468
0
      &encoder->priv->params);
2469
2470
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2471
2472
0
  return frame->output_buffer ? GST_FLOW_OK : GST_FLOW_ERROR;
2473
0
}
2474
2475
static void
2476
gst_video_encoder_release_frame_unlocked (GstVideoEncoder * enc,
2477
    GstVideoCodecFrame * frame)
2478
0
{
2479
0
  GList *link;
2480
2481
  /* unref once from the list */
2482
0
  link = g_queue_find (&enc->priv->frames, frame);
2483
0
  if (link) {
2484
0
    gst_video_codec_frame_unref (frame);
2485
0
    g_queue_delete_link (&enc->priv->frames, link);
2486
0
  }
2487
0
  if (frame->events) {
2488
0
    enc->priv->pending_events =
2489
0
        g_list_concat (frame->events, enc->priv->pending_events);
2490
0
    frame->events = NULL;
2491
0
  }
2492
2493
  /* unref because this function takes ownership */
2494
0
  gst_video_codec_frame_unref (frame);
2495
0
}
2496
2497
/**
2498
 * gst_video_encoder_release_frame:
2499
 * @encoder: a #GstVideoEncoder
2500
 * @frame: (transfer full): a #GstVideoCodecFrame
2501
 *
2502
 * Removes @frame from list of pending frames and releases it, similar
2503
 * to calling gst_video_encoder_finish_frame() without a buffer attached
2504
 * to the frame, but does not post a QoS message or do any additional
2505
 * processing. Events from @frame are moved to the pending events list.
2506
 *
2507
 * Since: 1.26
2508
 */
2509
void
2510
gst_video_encoder_release_frame (GstVideoEncoder * enc,
2511
    GstVideoCodecFrame * frame)
2512
0
{
2513
0
  g_return_if_fail (GST_IS_VIDEO_ENCODER (enc));
2514
0
  g_return_if_fail (frame != NULL);
2515
2516
0
  GST_LOG_OBJECT (enc, "Releasing frame %p", frame);
2517
2518
0
  GST_VIDEO_ENCODER_STREAM_LOCK (enc);
2519
0
  gst_video_encoder_release_frame_unlocked (enc, frame);
2520
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (enc);
2521
0
}
2522
2523
/**
2524
 * gst_video_encoder_drop_frame:
2525
 * @encoder: a #GstVideoEncoder
2526
 * @frame: (transfer full): a #GstVideoCodecFrame
2527
 *
2528
 * Removes @frame from the list of pending frames, releases it
2529
 * and posts a QoS message with the frame's details on the bus.
2530
 * Similar to calling gst_video_encoder_finish_frame() without a buffer
2531
 * attached to @frame, but this function additionally stores events
2532
 * from @frame as pending, to be pushed out alongside the next frame
2533
 * submitted via gst_video_encoder_finish_frame().
2534
 *
2535
 * Since: 1.26
2536
 */
2537
void
2538
gst_video_encoder_drop_frame (GstVideoEncoder * enc, GstVideoCodecFrame * frame)
2539
0
{
2540
0
  g_return_if_fail (GST_IS_VIDEO_ENCODER (enc));
2541
0
  g_return_if_fail (frame != NULL);
2542
2543
0
  GST_VIDEO_ENCODER_STREAM_LOCK (enc);
2544
2545
0
  GST_LOG_OBJECT (enc, "Dropping frame %p", frame);
2546
2547
0
  gst_video_encoder_push_pending_unlocked (enc, frame, TRUE);
2548
0
  gst_video_encoder_post_qos_drop (enc, frame);
2549
0
  gst_video_encoder_release_frame_unlocked (enc, frame);
2550
2551
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (enc);
2552
0
}
2553
2554
static gboolean
2555
gst_video_encoder_transform_meta_default (GstVideoEncoder *
2556
    encoder, GstVideoCodecFrame * frame, GstMeta * meta)
2557
0
{
2558
0
  const GstMetaInfo *info = meta->info;
2559
0
  const gchar *const *tags;
2560
0
  const gchar *const supported_tags[] = {
2561
0
    GST_META_TAG_VIDEO_STR,
2562
0
    GST_META_TAG_VIDEO_ORIENTATION_STR,
2563
0
    GST_META_TAG_VIDEO_SIZE_STR,
2564
0
    NULL,
2565
0
  };
2566
2567
0
  tags = gst_meta_api_type_get_tags (info->api);
2568
2569
0
  if (!tags)
2570
0
    return TRUE;
2571
2572
0
  while (*tags) {
2573
0
    if (!g_strv_contains (supported_tags, *tags))
2574
0
      return FALSE;
2575
0
    tags++;
2576
0
  }
2577
2578
0
  return TRUE;
2579
0
}
2580
2581
typedef struct
2582
{
2583
  GstVideoEncoder *encoder;
2584
  GstVideoCodecFrame *frame;
2585
} CopyMetaData;
2586
2587
static gboolean
2588
foreach_metadata (GstBuffer * inbuf, GstMeta ** meta, gpointer user_data)
2589
0
{
2590
0
  CopyMetaData *data = user_data;
2591
0
  GstVideoEncoder *encoder = data->encoder;
2592
0
  GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
2593
0
  GstVideoCodecFrame *frame = data->frame;
2594
0
  const GstMetaInfo *info = (*meta)->info;
2595
0
  gboolean do_copy = FALSE;
2596
2597
0
  if (gst_meta_api_type_has_tag (info->api, _gst_meta_tag_memory)
2598
0
      || gst_meta_api_type_has_tag (info->api, _gst_meta_tag_memory_reference)) {
2599
    /* never call the transform_meta with memory specific metadata */
2600
0
    GST_DEBUG_OBJECT (encoder, "not copying memory specific metadata %s",
2601
0
        g_type_name (info->api));
2602
0
    do_copy = FALSE;
2603
0
  } else if (klass->transform_meta) {
2604
0
    do_copy = klass->transform_meta (encoder, frame, *meta);
2605
0
    GST_DEBUG_OBJECT (encoder, "transformed metadata %s: copy: %d",
2606
0
        g_type_name (info->api), do_copy);
2607
0
  }
2608
2609
  /* we only copy metadata when the subclass implemented a transform_meta
2610
   * function and when it returns %TRUE */
2611
0
  if (do_copy && info->transform_func) {
2612
0
    GstMetaTransformCopy copy_data = { FALSE, 0, -1 };
2613
0
    GST_DEBUG_OBJECT (encoder, "copy metadata %s", g_type_name (info->api));
2614
    /* simply copy then */
2615
0
    info->transform_func (frame->output_buffer, *meta, inbuf,
2616
0
        _gst_meta_transform_copy, &copy_data);
2617
0
  }
2618
0
  return TRUE;
2619
0
}
2620
2621
/* called with STREAM_LOCK */
2622
static void
2623
gst_video_encoder_post_qos_drop (GstVideoEncoder * enc,
2624
    GstVideoCodecFrame * frame)
2625
0
{
2626
0
  GstVideoEncoderPrivate *priv = enc->priv;
2627
0
  GstClockTime stream_time, jitter, earliest_time, qostime, timestamp;
2628
0
  GstSegment *segment;
2629
0
  GstMessage *qos_msg;
2630
0
  gdouble proportion;
2631
2632
0
  GST_DEBUG_OBJECT (enc, "dropping frame %" GST_TIME_FORMAT,
2633
0
      GST_TIME_ARGS (frame->pts));
2634
2635
0
  priv->dropped++;
2636
2637
  /* post QoS message */
2638
0
  GST_OBJECT_LOCK (enc);
2639
0
  proportion = priv->proportion;
2640
0
  earliest_time = priv->earliest_time;
2641
0
  GST_OBJECT_UNLOCK (enc);
2642
2643
0
  timestamp = frame->pts;
2644
0
  segment = &enc->output_segment;
2645
0
  if (G_UNLIKELY (segment->format == GST_FORMAT_UNDEFINED))
2646
0
    segment = &enc->input_segment;
2647
0
  stream_time =
2648
0
      gst_segment_to_stream_time (segment, GST_FORMAT_TIME, timestamp);
2649
0
  qostime = gst_segment_to_running_time (segment, GST_FORMAT_TIME, timestamp);
2650
0
  jitter = GST_CLOCK_DIFF (qostime, earliest_time);
2651
0
  qos_msg =
2652
0
      gst_message_new_qos (GST_OBJECT_CAST (enc), FALSE, qostime, stream_time,
2653
0
      timestamp, GST_CLOCK_TIME_NONE);
2654
0
  gst_message_set_qos_values (qos_msg, jitter, proportion, 1000000);
2655
0
  gst_message_set_qos_stats (qos_msg, GST_FORMAT_BUFFERS,
2656
0
      priv->processed, priv->dropped);
2657
0
  gst_element_post_message (GST_ELEMENT_CAST (enc), qos_msg);
2658
0
}
2659
2660
static GstFlowReturn
2661
gst_video_encoder_can_push_unlocked (GstVideoEncoder * encoder)
2662
0
{
2663
0
  GstVideoEncoderPrivate *priv = encoder->priv;
2664
0
  gboolean needs_reconfigure;
2665
2666
0
  needs_reconfigure = gst_pad_check_reconfigure (encoder->srcpad);
2667
0
  if (G_UNLIKELY (priv->output_state_changed || (priv->output_state
2668
0
              && needs_reconfigure))) {
2669
0
    if (!gst_video_encoder_negotiate_unlocked (encoder)) {
2670
0
      gst_pad_mark_reconfigure (encoder->srcpad);
2671
0
      if (GST_PAD_IS_FLUSHING (encoder->srcpad))
2672
0
        return GST_FLOW_FLUSHING;
2673
0
      else
2674
0
        return GST_FLOW_NOT_NEGOTIATED;
2675
0
    }
2676
0
  }
2677
2678
0
  if (G_UNLIKELY (priv->output_state == NULL)) {
2679
0
    GST_ERROR_OBJECT (encoder, "Output state was not configured");
2680
0
    GST_ELEMENT_ERROR (encoder, LIBRARY, FAILED,
2681
0
        ("Output state was not configured"), (NULL));
2682
0
    return GST_FLOW_ERROR;
2683
0
  }
2684
2685
0
  return GST_FLOW_OK;
2686
0
}
2687
2688
static void
2689
gst_video_encoder_push_event_list (GstVideoEncoder * encoder, GList * events)
2690
0
{
2691
0
  GList *l;
2692
2693
  /* events are stored in reverse order */
2694
0
  for (l = g_list_last (events); l; l = g_list_previous (l)) {
2695
0
    GST_LOG_OBJECT (encoder, "pushing %s event", GST_EVENT_TYPE_NAME (l->data));
2696
0
    gst_video_encoder_push_event (encoder, l->data);
2697
0
  }
2698
0
  g_list_free (events);
2699
0
}
2700
2701
static void
2702
gst_video_encoder_push_pending_unlocked (GstVideoEncoder * encoder,
2703
    GstVideoCodecFrame * frame, gboolean dropping)
2704
0
{
2705
0
  GstVideoEncoderPrivate *priv = encoder->priv;
2706
0
  GList *l, *events = NULL;
2707
2708
  /* Push all pending events that arrived before this frame */
2709
0
  for (l = priv->frames.head; l; l = l->next) {
2710
0
    GstVideoCodecFrame *tmp = l->data;
2711
2712
0
    if (tmp->events) {
2713
0
      events = g_list_concat (tmp->events, events);
2714
0
      tmp->events = NULL;
2715
0
    }
2716
2717
0
    if (tmp == frame)
2718
0
      break;
2719
0
  }
2720
2721
0
  if (dropping) {
2722
    /* Push before the next frame that is not dropped */
2723
0
    priv->pending_events = g_list_concat (events, priv->pending_events);
2724
0
  } else {
2725
0
    gst_video_encoder_push_event_list (encoder, priv->pending_events);
2726
0
    priv->pending_events = NULL;
2727
2728
0
    gst_video_encoder_push_event_list (encoder, events);
2729
0
  }
2730
2731
0
  gst_video_encoder_check_and_push_tags (encoder);
2732
0
}
2733
2734
static void
2735
gst_video_encoder_infer_dts_unlocked (GstVideoEncoder * encoder,
2736
    GstVideoCodecFrame * frame)
2737
0
{
2738
  /* DTS is expected to be monotonously increasing,
2739
   * so a good guess is the lowest unsent PTS (all being OK) */
2740
0
  GstVideoEncoderPrivate *priv = encoder->priv;
2741
0
  GList *l;
2742
0
  GstClockTime min_ts = GST_CLOCK_TIME_NONE;
2743
0
  GstVideoCodecFrame *oframe = NULL;
2744
0
  gboolean seen_none = FALSE;
2745
2746
  /* some maintenance regardless */
2747
0
  for (l = priv->frames.head; l; l = l->next) {
2748
0
    GstVideoCodecFrame *tmp = l->data;
2749
2750
0
    if (!GST_CLOCK_TIME_IS_VALID (tmp->abidata.ABI.ts)) {
2751
0
      seen_none = TRUE;
2752
0
      continue;
2753
0
    }
2754
2755
0
    if (!GST_CLOCK_TIME_IS_VALID (min_ts) || tmp->abidata.ABI.ts < min_ts) {
2756
0
      min_ts = tmp->abidata.ABI.ts;
2757
0
      oframe = tmp;
2758
0
    }
2759
0
  }
2760
  /* save a ts if needed */
2761
0
  if (oframe && oframe != frame) {
2762
0
    oframe->abidata.ABI.ts = frame->abidata.ABI.ts;
2763
0
  }
2764
2765
  /* and set if needed */
2766
0
  if (!GST_CLOCK_TIME_IS_VALID (frame->dts) && !seen_none) {
2767
0
    frame->dts = min_ts;
2768
0
    GST_DEBUG_OBJECT (encoder,
2769
0
        "no valid DTS, using oldest PTS %" GST_TIME_FORMAT,
2770
0
        GST_TIME_ARGS (frame->pts));
2771
0
  }
2772
0
}
2773
2774
static void
2775
gst_video_encoder_send_header_unlocked (GstVideoEncoder * encoder,
2776
    gboolean * discont, gboolean key_unit)
2777
0
{
2778
0
  GstVideoEncoderPrivate *priv = encoder->priv;
2779
2780
0
  if (G_UNLIKELY (priv->new_headers)) {
2781
0
    GList *tmp;
2782
2783
0
    GST_DEBUG_OBJECT (encoder, "Sending headers");
2784
2785
    /* First make all buffers metadata-writable */
2786
0
    for (tmp = priv->headers; tmp; tmp = tmp->next) {
2787
0
      GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
2788
2789
0
      tmp->data = tmpbuf = gst_buffer_make_writable (tmpbuf);
2790
2791
0
      GST_OBJECT_LOCK (encoder);
2792
0
      priv->bytes += gst_buffer_get_size (tmpbuf);
2793
0
      GST_OBJECT_UNLOCK (encoder);
2794
2795
0
      if (G_UNLIKELY (key_unit)) {
2796
0
        key_unit = FALSE;
2797
0
        GST_BUFFER_FLAG_UNSET (tmpbuf, GST_BUFFER_FLAG_DELTA_UNIT);
2798
0
      } else {
2799
0
        GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DELTA_UNIT);
2800
0
      }
2801
2802
0
      if (G_UNLIKELY (*discont)) {
2803
0
        GST_LOG_OBJECT (encoder, "marking discont");
2804
0
        GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2805
0
        *discont = FALSE;
2806
0
      } else {
2807
0
        GST_BUFFER_FLAG_UNSET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2808
0
      }
2809
2810
0
      gst_pad_push (encoder->srcpad, gst_buffer_ref (tmpbuf));
2811
0
    }
2812
0
    priv->new_headers = FALSE;
2813
0
  }
2814
0
}
2815
2816
static void
2817
gst_video_encoder_transform_meta_unlocked (GstVideoEncoder * encoder,
2818
    GstVideoCodecFrame * frame)
2819
0
{
2820
0
  GstVideoEncoderClass *encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
2821
2822
0
  if (encoder_class->transform_meta) {
2823
0
    if (G_LIKELY (frame->input_buffer)) {
2824
0
      CopyMetaData data;
2825
2826
0
      data.encoder = encoder;
2827
0
      data.frame = frame;
2828
0
      gst_buffer_foreach_meta (frame->input_buffer, foreach_metadata, &data);
2829
0
    } else {
2830
0
      GST_FIXME_OBJECT (encoder,
2831
0
          "Can't copy metadata because input frame disappeared");
2832
0
    }
2833
0
  }
2834
0
}
2835
2836
static void
2837
gst_video_encoder_send_key_unit_unlocked (GstVideoEncoder * encoder,
2838
    GstVideoCodecFrame * frame, gboolean * send_headers)
2839
0
{
2840
0
  GstVideoEncoderPrivate *priv = encoder->priv;
2841
0
  GstClockTime stream_time, running_time;
2842
0
  GstEvent *ev;
2843
0
  GList *l;
2844
0
  GQueue matching_fevt = G_QUEUE_INIT;
2845
0
  ForcedKeyUnitEvent *fevt;
2846
2847
0
  running_time =
2848
0
      gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
2849
0
      frame->pts);
2850
2851
0
  GST_OBJECT_LOCK (encoder);
2852
0
  for (l = priv->force_key_unit.head; l;) {
2853
0
    fevt = l->data;
2854
2855
    /* Skip non-pending keyunits */
2856
0
    if (!fevt->pending) {
2857
0
      l = l->next;
2858
0
      continue;
2859
0
    }
2860
2861
    /* Exact match using the frame id */
2862
0
    if (frame->system_frame_number == fevt->frame_id) {
2863
0
      GList *next = l->next;
2864
0
      g_queue_push_tail (&matching_fevt, fevt);
2865
0
      g_queue_delete_link (&priv->force_key_unit, l);
2866
0
      l = next;
2867
0
      continue;
2868
0
    }
2869
2870
    /* Simple case, keyunit ASAP */
2871
0
    if (fevt->running_time == GST_CLOCK_TIME_NONE) {
2872
0
      GList *next = l->next;
2873
0
      g_queue_push_tail (&matching_fevt, fevt);
2874
0
      g_queue_delete_link (&priv->force_key_unit, l);
2875
0
      l = next;
2876
0
      continue;
2877
0
    }
2878
2879
    /* Event for before this frame */
2880
0
    if (fevt->running_time <= running_time) {
2881
0
      GList *next = l->next;
2882
0
      g_queue_push_tail (&matching_fevt, fevt);
2883
0
      g_queue_delete_link (&priv->force_key_unit, l);
2884
0
      l = next;
2885
0
      continue;
2886
0
    }
2887
2888
    /* Otherwise all following events are in the future */
2889
0
    break;
2890
0
  }
2891
2892
0
  GST_OBJECT_UNLOCK (encoder);
2893
2894
0
  while ((fevt = g_queue_pop_head (&matching_fevt))) {
2895
0
    stream_time =
2896
0
        gst_segment_to_stream_time (&encoder->output_segment, GST_FORMAT_TIME,
2897
0
        frame->pts);
2898
2899
0
    ev = gst_video_event_new_downstream_force_key_unit
2900
0
        (frame->pts, stream_time, running_time, fevt->all_headers, fevt->count);
2901
2902
0
    gst_video_encoder_push_event (encoder, ev);
2903
2904
0
    if (fevt->all_headers)
2905
0
      *send_headers = TRUE;
2906
2907
0
    GST_DEBUG_OBJECT (encoder,
2908
0
        "Forced key unit: running-time %" GST_TIME_FORMAT
2909
0
        ", all_headers %d, count %u",
2910
0
        GST_TIME_ARGS (running_time), fevt->all_headers, fevt->count);
2911
0
    forced_key_unit_event_free (fevt);
2912
0
  }
2913
0
}
2914
2915
/**
2916
 * gst_video_encoder_finish_frame:
2917
 * @encoder: a #GstVideoEncoder
2918
 * @frame: (transfer full): an encoded #GstVideoCodecFrame
2919
 *
2920
 * @frame must have a valid encoded data buffer, whose metadata fields
2921
 * are then appropriately set according to frame data or no buffer at
2922
 * all if the frame should be dropped.
2923
 * It is subsequently pushed downstream or provided to @pre_push.
2924
 * In any case, the frame is considered finished and released.
2925
 *
2926
 * If @frame does not have a buffer attached, it will be dropped, and
2927
 * a QoS message will be posted on the bus. Events from @frame will be
2928
 * pushed out immediately.
2929
 *
2930
 * After calling this function the output buffer of the frame is to be
2931
 * considered read-only. This function will also change the metadata
2932
 * of the buffer.
2933
 *
2934
 * Returns: a #GstFlowReturn resulting from sending data downstream
2935
 */
2936
GstFlowReturn
2937
gst_video_encoder_finish_frame (GstVideoEncoder * encoder,
2938
    GstVideoCodecFrame * frame)
2939
0
{
2940
0
  GstVideoEncoderPrivate *priv = encoder->priv;
2941
0
  GstFlowReturn ret = GST_FLOW_OK;
2942
0
  GstVideoEncoderClass *encoder_class;
2943
0
  gboolean send_headers = FALSE;
2944
0
  gboolean key_unit = FALSE;
2945
0
  gboolean discont = FALSE;
2946
0
  GstBuffer *buffer;
2947
2948
0
  g_return_val_if_fail (frame, GST_FLOW_ERROR);
2949
2950
0
  discont = (frame->presentation_frame_number == 0
2951
0
      && frame->abidata.ABI.num_subframes == 0);
2952
2953
0
  encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
2954
2955
0
  GST_LOG_OBJECT (encoder,
2956
0
      "finish frame fpn %d sync point: %d", frame->presentation_frame_number,
2957
0
      GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame));
2958
2959
0
  GST_LOG_OBJECT (encoder, "frame PTS %" GST_TIME_FORMAT
2960
0
      ", DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (frame->pts),
2961
0
      GST_TIME_ARGS (frame->dts));
2962
2963
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2964
2965
0
  ret = gst_video_encoder_can_push_unlocked (encoder);
2966
0
  if (ret != GST_FLOW_OK)
2967
0
    goto done;
2968
2969
0
  if (frame->abidata.ABI.num_subframes == 0)
2970
0
    gst_video_encoder_push_pending_unlocked (encoder, frame, FALSE);
2971
2972
  /* no buffer data means this frame is skipped/dropped */
2973
0
  if (!frame->output_buffer) {
2974
0
    gst_video_encoder_post_qos_drop (encoder, frame);
2975
0
    goto done;
2976
0
  }
2977
2978
0
  priv->processed++;
2979
2980
0
  if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame) && priv->force_key_unit.head)
2981
0
    gst_video_encoder_send_key_unit_unlocked (encoder, frame, &send_headers);
2982
2983
0
  if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)
2984
0
      && frame->abidata.ABI.num_subframes == 0) {
2985
0
    priv->distance_from_sync = 0;
2986
0
    key_unit = TRUE;
2987
    /* For keyframes, DTS = PTS, if encoder doesn't decide otherwise */
2988
0
    if (!GST_CLOCK_TIME_IS_VALID (frame->dts)) {
2989
0
      frame->dts = frame->pts;
2990
0
    }
2991
0
    priv->last_key_unit =
2992
0
        gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
2993
0
        frame->pts);
2994
0
  }
2995
2996
0
  gst_video_encoder_infer_dts_unlocked (encoder, frame);
2997
2998
0
  frame->distance_from_sync = priv->distance_from_sync;
2999
0
  priv->distance_from_sync++;
3000
3001
  /* We need a writable buffer for the metadata changes below */
3002
0
  frame->output_buffer = gst_buffer_make_writable (frame->output_buffer);
3003
3004
0
  GST_BUFFER_PTS (frame->output_buffer) = frame->pts;
3005
0
  GST_BUFFER_DTS (frame->output_buffer) = frame->dts;
3006
0
  GST_BUFFER_DURATION (frame->output_buffer) = frame->duration;
3007
3008
  /* At this stage we have a full frame in subframe use case ,
3009
   * let's mark it to enabled some latency optimization
3010
   *  in some uses cases like RTP. */
3011
3012
0
  GST_BUFFER_FLAG_SET (frame->output_buffer, GST_VIDEO_BUFFER_FLAG_MARKER);
3013
3014
0
  GST_OBJECT_LOCK (encoder);
3015
  /* update rate estimate */
3016
0
  priv->bytes += gst_buffer_get_size (frame->output_buffer);
3017
0
  if (GST_CLOCK_TIME_IS_VALID (frame->duration)) {
3018
0
    priv->time += frame->duration;
3019
0
  } else {
3020
    /* better none than nothing valid */
3021
0
    priv->time = GST_CLOCK_TIME_NONE;
3022
0
  }
3023
0
  GST_OBJECT_UNLOCK (encoder);
3024
3025
0
  if (G_UNLIKELY (send_headers))
3026
0
    priv->new_headers = TRUE;
3027
3028
0
  gst_video_encoder_send_header_unlocked (encoder, &discont, key_unit);
3029
3030
0
  if (key_unit) {
3031
0
    GST_BUFFER_FLAG_UNSET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
3032
0
  } else {
3033
0
    GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
3034
0
  }
3035
3036
0
  if (G_UNLIKELY (discont)) {
3037
0
    GST_LOG_OBJECT (encoder, "marking discont");
3038
0
    GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DISCONT);
3039
0
  }
3040
3041
0
  if (encoder_class->pre_push)
3042
0
    ret = encoder_class->pre_push (encoder, frame);
3043
3044
0
  if (ret != GST_FLOW_OK)
3045
0
    goto done;
3046
3047
0
  gst_video_encoder_transform_meta_unlocked (encoder, frame);
3048
3049
  /* Get an additional ref to the buffer, which is going to be pushed
3050
   * downstream, the original ref is owned by the frame */
3051
0
  buffer = gst_buffer_ref (frame->output_buffer);
3052
3053
  /* Release frame so the buffer is writable when we push it downstream
3054
   * if possible, i.e. if the subclass does not hold additional references
3055
   * to the frame
3056
   */
3057
0
  gst_video_encoder_release_frame_unlocked (encoder, frame);
3058
0
  frame = NULL;
3059
3060
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
3061
0
  ret = gst_pad_push (encoder->srcpad, buffer);
3062
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
3063
3064
0
done:
3065
  /* handed out */
3066
0
  if (frame)
3067
0
    gst_video_encoder_release_frame_unlocked (encoder, frame);
3068
3069
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
3070
3071
0
  return ret;
3072
0
}
3073
3074
/**
3075
 * gst_video_encoder_finish_subframe:
3076
 * @encoder: a #GstVideoEncoder
3077
 * @frame: (transfer none): a #GstVideoCodecFrame being encoded
3078
 *
3079
 * If multiple subframes are produced for one input frame then use this method
3080
 * for each subframe, except for the last one. Before calling this function,
3081
 * you need to fill frame->output_buffer with the encoded buffer to push.
3082
3083
 * You must call #gst_video_encoder_finish_frame() for the last sub-frame
3084
 * to tell the encoder that the frame has been fully encoded.
3085
 *
3086
 * This function will change the metadata of @frame and frame->output_buffer
3087
 * will be pushed downstream.
3088
 *
3089
 * Returns: a #GstFlowReturn resulting from pushing the buffer downstream.
3090
 *
3091
 * Since: 1.18
3092
 */
3093
GstFlowReturn
3094
gst_video_encoder_finish_subframe (GstVideoEncoder * encoder,
3095
    GstVideoCodecFrame * frame)
3096
0
{
3097
0
  GstVideoEncoderPrivate *priv = encoder->priv;
3098
0
  GstVideoEncoderClass *encoder_class;
3099
0
  GstFlowReturn ret = GST_FLOW_OK;
3100
0
  GstBuffer *subframe_buffer = NULL;
3101
0
  gboolean discont = FALSE;
3102
0
  gboolean send_headers = FALSE;
3103
0
  gboolean key_unit = FALSE;
3104
3105
0
  g_return_val_if_fail (frame, GST_FLOW_ERROR);
3106
0
  g_return_val_if_fail (frame->output_buffer, GST_FLOW_ERROR);
3107
3108
0
  subframe_buffer = frame->output_buffer;
3109
3110
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
3111
0
  discont = (frame->presentation_frame_number == 0
3112
0
      && frame->abidata.ABI.num_subframes == 0);
3113
3114
0
  encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
3115
3116
0
  GST_LOG_OBJECT (encoder,
3117
0
      "finish subframe %u of frame fpn %u PTS %" GST_TIME_FORMAT ", DTS %"
3118
0
      GST_TIME_FORMAT " sync point: %d", frame->abidata.ABI.num_subframes,
3119
0
      frame->presentation_frame_number, GST_TIME_ARGS (frame->pts),
3120
0
      GST_TIME_ARGS (frame->dts), GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame));
3121
3122
0
  ret = gst_video_encoder_can_push_unlocked (encoder);
3123
0
  if (ret != GST_FLOW_OK)
3124
0
    goto done;
3125
3126
0
  if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame) && priv->force_key_unit.head)
3127
0
    gst_video_encoder_send_key_unit_unlocked (encoder, frame, &send_headers);
3128
3129
  /* Push pending events only for the first subframe ie segment event.
3130
   * Push new incoming events on finish_frame otherwise.
3131
   */
3132
0
  if (frame->abidata.ABI.num_subframes == 0)
3133
0
    gst_video_encoder_push_pending_unlocked (encoder, frame, FALSE);
3134
3135
0
  if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)
3136
0
      && frame->abidata.ABI.num_subframes == 0) {
3137
0
    priv->distance_from_sync = 0;
3138
0
    key_unit = TRUE;
3139
    /* For keyframes, DTS = PTS, if encoder doesn't decide otherwise */
3140
0
    if (!GST_CLOCK_TIME_IS_VALID (frame->dts)) {
3141
0
      frame->dts = frame->pts;
3142
0
    }
3143
0
    priv->last_key_unit =
3144
0
        gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
3145
0
        frame->pts);
3146
0
  }
3147
3148
0
  gst_video_encoder_infer_dts_unlocked (encoder, frame);
3149
3150
  /* We need a writable buffer for the metadata changes below */
3151
0
  subframe_buffer = gst_buffer_make_writable (subframe_buffer);
3152
3153
0
  GST_BUFFER_PTS (subframe_buffer) = frame->pts;
3154
0
  GST_BUFFER_DTS (subframe_buffer) = frame->dts;
3155
0
  GST_BUFFER_DURATION (subframe_buffer) = frame->duration;
3156
3157
0
  GST_OBJECT_LOCK (encoder);
3158
  /* update rate estimate */
3159
0
  priv->bytes += gst_buffer_get_size (subframe_buffer);
3160
0
  GST_OBJECT_UNLOCK (encoder);
3161
3162
0
  if (G_UNLIKELY (send_headers))
3163
0
    priv->new_headers = TRUE;
3164
3165
0
  gst_video_encoder_send_header_unlocked (encoder, &discont, key_unit);
3166
3167
0
  if (key_unit) {
3168
0
    GST_BUFFER_FLAG_UNSET (subframe_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
3169
0
  } else {
3170
0
    GST_BUFFER_FLAG_SET (subframe_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
3171
0
  }
3172
3173
0
  if (G_UNLIKELY (discont)) {
3174
0
    GST_LOG_OBJECT (encoder, "marking discont buffer: %" GST_PTR_FORMAT,
3175
0
        subframe_buffer);
3176
0
    GST_BUFFER_FLAG_SET (subframe_buffer, GST_BUFFER_FLAG_DISCONT);
3177
0
  }
3178
3179
0
  if (encoder_class->pre_push) {
3180
0
    ret = encoder_class->pre_push (encoder, frame);
3181
0
  }
3182
3183
0
  gst_video_encoder_transform_meta_unlocked (encoder, frame);
3184
3185
0
  if (ret == GST_FLOW_OK) {
3186
0
    GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
3187
0
    ret = gst_pad_push (encoder->srcpad, subframe_buffer);
3188
0
    subframe_buffer = NULL;
3189
0
    GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
3190
0
  }
3191
3192
0
done:
3193
0
  frame->abidata.ABI.num_subframes++;
3194
0
  if (subframe_buffer)
3195
0
    gst_buffer_unref (subframe_buffer);
3196
0
  frame->output_buffer = NULL;
3197
3198
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
3199
3200
0
  return ret;
3201
0
}
3202
3203
/**
3204
 * gst_video_encoder_get_output_state:
3205
 * @encoder: a #GstVideoEncoder
3206
 *
3207
 * Get the current #GstVideoCodecState
3208
 *
3209
 * Returns: (transfer full) (nullable): #GstVideoCodecState describing format of video data.
3210
 */
3211
GstVideoCodecState *
3212
gst_video_encoder_get_output_state (GstVideoEncoder * encoder)
3213
0
{
3214
0
  GstVideoCodecState *state = NULL;
3215
3216
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
3217
0
  if (encoder->priv->output_state)
3218
0
    state = gst_video_codec_state_ref (encoder->priv->output_state);
3219
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
3220
3221
0
  return state;
3222
0
}
3223
3224
/**
3225
 * gst_video_encoder_set_output_state:
3226
 * @encoder: a #GstVideoEncoder
3227
 * @caps: (transfer full): the #GstCaps to use for the output
3228
 * @reference: (nullable) (transfer none): An optional reference @GstVideoCodecState
3229
 *
3230
 * Creates a new #GstVideoCodecState with the specified caps as the output state
3231
 * for the encoder.
3232
 * Any previously set output state on @encoder will be replaced by the newly
3233
 * created one.
3234
 *
3235
 * The specified @caps should not contain any resolution, pixel-aspect-ratio,
3236
 * framerate, codec-data, .... Those should be specified instead in the returned
3237
 * #GstVideoCodecState.
3238
 *
3239
 * If the subclass wishes to copy over existing fields (like pixel aspect ratio,
3240
 * or framerate) from an existing #GstVideoCodecState, it can be provided as a
3241
 * @reference.
3242
 *
3243
 * If the subclass wishes to override some fields from the output state (like
3244
 * pixel-aspect-ratio or framerate) it can do so on the returned #GstVideoCodecState.
3245
 *
3246
 * The new output state will only take effect (set on pads and buffers) starting
3247
 * from the next call to #gst_video_encoder_finish_frame().
3248
 *
3249
 * Returns: (transfer full) (nullable): the newly configured output state.
3250
 */
3251
GstVideoCodecState *
3252
gst_video_encoder_set_output_state (GstVideoEncoder * encoder, GstCaps * caps,
3253
    GstVideoCodecState * reference)
3254
0
{
3255
0
  GstVideoEncoderPrivate *priv = encoder->priv;
3256
0
  GstVideoCodecState *state;
3257
3258
0
  g_return_val_if_fail (caps != NULL, NULL);
3259
3260
0
  state = _new_output_state (caps, reference);
3261
0
  if (!state)
3262
0
    return NULL;
3263
3264
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
3265
0
  if (priv->output_state)
3266
0
    gst_video_codec_state_unref (priv->output_state);
3267
0
  priv->output_state = gst_video_codec_state_ref (state);
3268
3269
0
  if (priv->output_state != NULL && priv->output_state->info.fps_n > 0) {
3270
0
    priv->qos_frame_duration =
3271
0
        gst_util_uint64_scale (GST_SECOND, priv->output_state->info.fps_d,
3272
0
        priv->output_state->info.fps_n);
3273
0
  } else {
3274
0
    priv->qos_frame_duration = 0;
3275
0
  }
3276
3277
0
  priv->output_state_changed = TRUE;
3278
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
3279
3280
0
  return state;
3281
0
}
3282
3283
/**
3284
 * gst_video_encoder_set_latency:
3285
 * @encoder: a #GstVideoEncoder
3286
 * @min_latency: minimum latency
3287
 * @max_latency: maximum latency
3288
 *
3289
 * Informs baseclass of encoding latency. If the provided values changed from
3290
 * previously provided ones, this will also post a LATENCY message on the bus
3291
 * so the pipeline can reconfigure its global latency.
3292
 */
3293
void
3294
gst_video_encoder_set_latency (GstVideoEncoder * encoder,
3295
    GstClockTime min_latency, GstClockTime max_latency)
3296
0
{
3297
0
  gboolean post_message = FALSE;
3298
3299
0
  g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
3300
0
  g_return_if_fail (max_latency >= min_latency);
3301
3302
0
  GST_DEBUG_OBJECT (encoder,
3303
0
      "min_latency:%" GST_TIME_FORMAT " max_latency:%" GST_TIME_FORMAT,
3304
0
      GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3305
3306
0
  GST_OBJECT_LOCK (encoder);
3307
0
  if (encoder->priv->min_latency != min_latency) {
3308
0
    encoder->priv->min_latency = min_latency;
3309
0
    post_message = TRUE;
3310
0
  }
3311
0
  if (encoder->priv->max_latency != max_latency) {
3312
0
    encoder->priv->max_latency = max_latency;
3313
0
    post_message = TRUE;
3314
0
  }
3315
0
  if (!encoder->priv->posted_latency_msg) {
3316
0
    encoder->priv->posted_latency_msg = TRUE;
3317
0
    post_message = TRUE;
3318
0
  }
3319
0
  GST_OBJECT_UNLOCK (encoder);
3320
3321
0
  if (post_message)
3322
0
    gst_element_post_message (GST_ELEMENT_CAST (encoder),
3323
0
        gst_message_new_latency (GST_OBJECT_CAST (encoder)));
3324
0
}
3325
3326
/**
3327
 * gst_video_encoder_get_latency:
3328
 * @encoder: a #GstVideoEncoder
3329
 * @min_latency: (out) (optional): address of variable in which to store the
3330
 *     configured minimum latency, or %NULL
3331
 * @max_latency: (out) (optional): address of variable in which to store the
3332
 *     configured maximum latency, or %NULL
3333
 *
3334
 * Query the configured encoding latency. Results will be returned via
3335
 * @min_latency and @max_latency.
3336
 */
3337
void
3338
gst_video_encoder_get_latency (GstVideoEncoder * encoder,
3339
    GstClockTime * min_latency, GstClockTime * max_latency)
3340
0
{
3341
0
  GST_OBJECT_LOCK (encoder);
3342
0
  if (min_latency)
3343
0
    *min_latency = encoder->priv->min_latency;
3344
0
  if (max_latency)
3345
0
    *max_latency = encoder->priv->max_latency;
3346
0
  GST_OBJECT_UNLOCK (encoder);
3347
0
}
3348
3349
/**
3350
 * gst_video_encoder_get_oldest_frame:
3351
 * @encoder: a #GstVideoEncoder
3352
 *
3353
 * Get the oldest unfinished pending #GstVideoCodecFrame
3354
 *
3355
 * Returns: (transfer full) (nullable): oldest unfinished pending #GstVideoCodecFrame
3356
 */
3357
GstVideoCodecFrame *
3358
gst_video_encoder_get_oldest_frame (GstVideoEncoder * encoder)
3359
0
{
3360
0
  GstVideoCodecFrame *frame = NULL;
3361
3362
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
3363
0
  if (encoder->priv->frames.head)
3364
0
    frame = gst_video_codec_frame_ref (encoder->priv->frames.head->data);
3365
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
3366
3367
0
  return (GstVideoCodecFrame *) frame;
3368
0
}
3369
3370
/**
3371
 * gst_video_encoder_get_frame:
3372
 * @encoder: a #GstVideoEncoder
3373
 * @frame_number: system_frame_number of a frame
3374
 *
3375
 * Get a pending unfinished #GstVideoCodecFrame
3376
 *
3377
 * Returns: (transfer full) (nullable): pending unfinished #GstVideoCodecFrame identified by @frame_number.
3378
 */
3379
GstVideoCodecFrame *
3380
gst_video_encoder_get_frame (GstVideoEncoder * encoder, int frame_number)
3381
0
{
3382
0
  GList *g;
3383
0
  GstVideoCodecFrame *frame = NULL;
3384
3385
0
  GST_DEBUG_OBJECT (encoder, "frame_number : %d", frame_number);
3386
3387
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
3388
0
  for (g = encoder->priv->frames.head; g; g = g->next) {
3389
0
    GstVideoCodecFrame *tmp = g->data;
3390
3391
0
    if (tmp->system_frame_number == frame_number) {
3392
0
      frame = gst_video_codec_frame_ref (tmp);
3393
0
      break;
3394
0
    }
3395
0
  }
3396
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
3397
3398
0
  return frame;
3399
0
}
3400
3401
/**
3402
 * gst_video_encoder_get_frames:
3403
 * @encoder: a #GstVideoEncoder
3404
 *
3405
 * Get all pending unfinished #GstVideoCodecFrame
3406
 *
3407
 * Returns: (transfer full) (element-type GstVideoCodecFrame): pending unfinished #GstVideoCodecFrame.
3408
 */
3409
GList *
3410
gst_video_encoder_get_frames (GstVideoEncoder * encoder)
3411
0
{
3412
0
  GList *frames;
3413
3414
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
3415
0
  frames =
3416
0
      g_list_copy_deep (encoder->priv->frames.head,
3417
0
      (GCopyFunc) gst_video_codec_frame_ref, NULL);
3418
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
3419
3420
0
  return frames;
3421
0
}
3422
3423
/**
3424
 * gst_video_encoder_merge_tags:
3425
 * @encoder: a #GstVideoEncoder
3426
 * @tags: (nullable): a #GstTagList to merge, or NULL to unset
3427
 *     previously-set tags
3428
 * @mode: the #GstTagMergeMode to use, usually #GST_TAG_MERGE_REPLACE
3429
 *
3430
 * Sets the video encoder tags and how they should be merged with any
3431
 * upstream stream tags. This will override any tags previously-set
3432
 * with gst_video_encoder_merge_tags().
3433
 *
3434
 * Note that this is provided for convenience, and the subclass is
3435
 * not required to use this and can still do tag handling on its own.
3436
 *
3437
 * MT safe.
3438
 */
3439
void
3440
gst_video_encoder_merge_tags (GstVideoEncoder * encoder,
3441
    const GstTagList * tags, GstTagMergeMode mode)
3442
0
{
3443
0
  g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
3444
0
  g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
3445
0
  g_return_if_fail (tags == NULL || mode != GST_TAG_MERGE_UNDEFINED);
3446
3447
0
  GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
3448
0
  if (encoder->priv->tags != tags) {
3449
0
    if (encoder->priv->tags) {
3450
0
      gst_tag_list_unref (encoder->priv->tags);
3451
0
      encoder->priv->tags = NULL;
3452
0
      encoder->priv->tags_merge_mode = GST_TAG_MERGE_APPEND;
3453
0
    }
3454
0
    if (tags) {
3455
0
      encoder->priv->tags = gst_tag_list_ref ((GstTagList *) tags);
3456
0
      encoder->priv->tags_merge_mode = mode;
3457
0
    }
3458
3459
0
    GST_DEBUG_OBJECT (encoder, "setting encoder tags to %" GST_PTR_FORMAT,
3460
0
        tags);
3461
0
    encoder->priv->tags_changed = TRUE;
3462
0
  }
3463
0
  GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
3464
0
}
3465
3466
/**
3467
 * gst_video_encoder_get_allocator:
3468
 * @encoder: a #GstVideoEncoder
3469
 * @allocator: (out) (optional) (nullable) (transfer full): the #GstAllocator
3470
 * used
3471
 * @params: (out) (optional) (transfer full): the
3472
 * #GstAllocationParams of @allocator
3473
 *
3474
 * Lets #GstVideoEncoder sub-classes to know the memory @allocator
3475
 * used by the base class and its @params.
3476
 *
3477
 * Unref the @allocator after use it.
3478
 */
3479
void
3480
gst_video_encoder_get_allocator (GstVideoEncoder * encoder,
3481
    GstAllocator ** allocator, GstAllocationParams * params)
3482
0
{
3483
0
  g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
3484
3485
0
  if (allocator)
3486
0
    *allocator = encoder->priv->allocator ?
3487
0
        gst_object_ref (encoder->priv->allocator) : NULL;
3488
3489
0
  if (params)
3490
0
    *params = encoder->priv->params;
3491
0
}
3492
3493
/**
3494
 * gst_video_encoder_set_min_pts:
3495
 * @encoder: a #GstVideoEncoder
3496
 * @min_pts: minimal PTS that will be passed to handle_frame
3497
 *
3498
 * Request minimal value for PTS passed to handle_frame.
3499
 *
3500
 * For streams with reordered frames this can be used to ensure that there
3501
 * is enough time to accommodate first DTS, which may be less than first PTS
3502
 *
3503
 * Since: 1.6
3504
 */
3505
void
3506
gst_video_encoder_set_min_pts (GstVideoEncoder * encoder, GstClockTime min_pts)
3507
0
{
3508
0
  g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
3509
0
  encoder->priv->min_pts = min_pts;
3510
0
  encoder->priv->time_adjustment = GST_CLOCK_TIME_NONE;
3511
0
}
3512
3513
/**
3514
 * gst_video_encoder_get_max_encode_time:
3515
 * @encoder: a #GstVideoEncoder
3516
 * @frame: a #GstVideoCodecFrame
3517
 *
3518
 * Determines maximum possible encoding time for @frame that will
3519
 * allow it to encode and arrive in time (as determined by QoS events).
3520
 * In particular, a negative result means encoding in time is no longer possible
3521
 * and should therefore occur as soon/skippy as possible.
3522
 *
3523
 * If no QoS events have been received from downstream, or if
3524
 * #GstVideoEncoder:qos is disabled this function returns #G_MAXINT64.
3525
 *
3526
 * Returns: max decoding time.
3527
 * Since: 1.14
3528
 */
3529
GstClockTimeDiff
3530
gst_video_encoder_get_max_encode_time (GstVideoEncoder *
3531
    encoder, GstVideoCodecFrame * frame)
3532
0
{
3533
0
  GstClockTimeDiff deadline;
3534
0
  GstClockTime earliest_time;
3535
3536
0
  if (!g_atomic_int_get (&encoder->priv->qos_enabled))
3537
0
    return G_MAXINT64;
3538
3539
0
  GST_OBJECT_LOCK (encoder);
3540
0
  earliest_time = encoder->priv->earliest_time;
3541
0
  if (GST_CLOCK_TIME_IS_VALID (earliest_time)
3542
0
      && GST_CLOCK_TIME_IS_VALID (frame->deadline))
3543
0
    deadline = GST_CLOCK_DIFF (earliest_time, frame->deadline);
3544
0
  else
3545
0
    deadline = G_MAXINT64;
3546
3547
0
  GST_LOG_OBJECT (encoder, "earliest %" GST_TIME_FORMAT
3548
0
      ", frame deadline %" GST_TIME_FORMAT ", deadline %" GST_STIME_FORMAT,
3549
0
      GST_TIME_ARGS (earliest_time), GST_TIME_ARGS (frame->deadline),
3550
0
      GST_STIME_ARGS (deadline));
3551
3552
0
  GST_OBJECT_UNLOCK (encoder);
3553
3554
0
  return deadline;
3555
0
}
3556
3557
/**
3558
 * gst_video_encoder_set_qos_enabled:
3559
 * @encoder: the encoder
3560
 * @enabled: the new qos value.
3561
 *
3562
 * Configures @encoder to handle Quality-of-Service events from downstream.
3563
 * Since: 1.14
3564
 */
3565
void
3566
gst_video_encoder_set_qos_enabled (GstVideoEncoder * encoder, gboolean enabled)
3567
0
{
3568
0
  g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
3569
3570
0
  g_atomic_int_set (&encoder->priv->qos_enabled, enabled);
3571
0
}
3572
3573
/**
3574
 * gst_video_encoder_is_qos_enabled:
3575
 * @encoder: the encoder
3576
 *
3577
 * Checks if @encoder is currently configured to handle Quality-of-Service
3578
 * events from downstream.
3579
 *
3580
 * Returns: %TRUE if the encoder is configured to perform Quality-of-Service.
3581
 * Since: 1.14
3582
 */
3583
gboolean
3584
gst_video_encoder_is_qos_enabled (GstVideoEncoder * encoder)
3585
0
{
3586
0
  gboolean res;
3587
3588
0
  g_return_val_if_fail (GST_IS_VIDEO_ENCODER (encoder), FALSE);
3589
3590
0
  res = g_atomic_int_get (&encoder->priv->qos_enabled);
3591
3592
0
  return res;
3593
0
}
3594
3595
/**
3596
 * gst_video_encoder_set_min_force_key_unit_interval:
3597
 * @encoder: the encoder
3598
 * @interval: minimum interval
3599
 *
3600
 * Sets the minimum interval for requesting keyframes based on force-keyunit
3601
 * events. Setting this to 0 will allow to handle every event, setting this to
3602
 * %GST_CLOCK_TIME_NONE causes force-keyunit events to be ignored.
3603
 *
3604
 * Since: 1.18
3605
 */
3606
void
3607
gst_video_encoder_set_min_force_key_unit_interval (GstVideoEncoder * encoder,
3608
    GstClockTime interval)
3609
0
{
3610
0
  g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
3611
3612
0
  GST_OBJECT_LOCK (encoder);
3613
0
  encoder->priv->min_force_key_unit_interval = interval;
3614
0
  GST_OBJECT_UNLOCK (encoder);
3615
0
}
3616
3617
/**
3618
 * gst_video_encoder_get_min_force_key_unit_interval:
3619
 * @encoder: the encoder
3620
 *
3621
 * Returns the minimum force-keyunit interval, see gst_video_encoder_set_min_force_key_unit_interval()
3622
 * for more details.
3623
 *
3624
 * Returns: the minimum force-keyunit interval
3625
 *
3626
 * Since: 1.18
3627
 */
3628
GstClockTime
3629
gst_video_encoder_get_min_force_key_unit_interval (GstVideoEncoder * encoder)
3630
0
{
3631
0
  GstClockTime interval;
3632
3633
0
  g_return_val_if_fail (GST_IS_VIDEO_ENCODER (encoder), GST_CLOCK_TIME_NONE);
3634
3635
0
  GST_OBJECT_LOCK (encoder);
3636
0
  interval = encoder->priv->min_force_key_unit_interval;
3637
0
  GST_OBJECT_UNLOCK (encoder);
3638
3639
0
  return interval;
3640
0
}