avdeinterlace: fix element leak
[platform/upstream/gstreamer.git] / subprojects / gst-libav / ext / libav / gstavauddec.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  * Copyright (C) <2012> Collabora Ltd.
4  *   Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include <assert.h>
27 #include <string.h>
28
29 #include <libavcodec/avcodec.h>
30 #include <libavutil/channel_layout.h>
31
32 #include <gst/gst.h>
33 #include <gst/base/gstbytewriter.h>
34
35 #include "gstav.h"
36 #include "gstavcodecmap.h"
37 #include "gstavutils.h"
38 #include "gstavauddec.h"
39
40 GST_DEBUG_CATEGORY_STATIC (GST_CAT_PERFORMANCE);
41
42 /* A number of function prototypes are given so we can refer to them later. */
43 static void gst_ffmpegauddec_base_init (GstFFMpegAudDecClass * klass);
44 static void gst_ffmpegauddec_class_init (GstFFMpegAudDecClass * klass);
45 static void gst_ffmpegauddec_init (GstFFMpegAudDec * ffmpegdec);
46 static void gst_ffmpegauddec_finalize (GObject * object);
47 static gboolean gst_ffmpegauddec_propose_allocation (GstAudioDecoder * decoder,
48     GstQuery * query);
49
50 static gboolean gst_ffmpegauddec_start (GstAudioDecoder * decoder);
51 static gboolean gst_ffmpegauddec_stop (GstAudioDecoder * decoder);
52 static void gst_ffmpegauddec_flush (GstAudioDecoder * decoder, gboolean hard);
53 static gboolean gst_ffmpegauddec_set_format (GstAudioDecoder * decoder,
54     GstCaps * caps);
55 static GstFlowReturn gst_ffmpegauddec_handle_frame (GstAudioDecoder * decoder,
56     GstBuffer * inbuf);
57
58 static gboolean gst_ffmpegauddec_negotiate (GstFFMpegAudDec * ffmpegdec,
59     AVCodecContext * context, AVFrame * frame, gboolean force);
60
61 static GstFlowReturn gst_ffmpegauddec_drain (GstFFMpegAudDec * ffmpegdec,
62     gboolean force);
63
64 #define GST_FFDEC_PARAMS_QDATA g_quark_from_static_string("avdec-params")
65
66 static GstElementClass *parent_class = NULL;
67
68 static void
69 gst_ffmpegauddec_base_init (GstFFMpegAudDecClass * klass)
70 {
71   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
72   GstPadTemplate *sinktempl, *srctempl;
73   GstCaps *sinkcaps, *srccaps;
74   AVCodec *in_plugin;
75   gchar *longname, *description;
76
77   in_plugin =
78       (AVCodec *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (klass),
79       GST_FFDEC_PARAMS_QDATA);
80   g_assert (in_plugin != NULL);
81
82   /* construct the element details struct */
83   longname = g_strdup_printf ("libav %s decoder", in_plugin->long_name);
84   description = g_strdup_printf ("libav %s decoder", in_plugin->name);
85   gst_element_class_set_metadata (element_class, longname,
86       "Codec/Decoder/Audio", description,
87       "Wim Taymans <wim.taymans@gmail.com>, "
88       "Ronald Bultje <rbultje@ronald.bitfreak.net>, "
89       "Edward Hervey <bilboed@bilboed.com>");
90   g_free (longname);
91   g_free (description);
92
93   /* get the caps */
94   sinkcaps = gst_ffmpeg_codecid_to_caps (in_plugin->id, NULL, FALSE);
95   if (!sinkcaps) {
96     GST_DEBUG ("Couldn't get sink caps for decoder '%s'", in_plugin->name);
97     sinkcaps = gst_caps_from_string ("unknown/unknown");
98   }
99   srccaps = gst_ffmpeg_codectype_to_audio_caps (NULL,
100       in_plugin->id, FALSE, in_plugin);
101   if (!srccaps) {
102     GST_DEBUG ("Couldn't get source caps for decoder '%s'", in_plugin->name);
103     srccaps = gst_caps_from_string ("audio/x-raw");
104   }
105
106   /* pad templates */
107   sinktempl = gst_pad_template_new ("sink", GST_PAD_SINK,
108       GST_PAD_ALWAYS, sinkcaps);
109   srctempl = gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS, srccaps);
110
111   gst_element_class_add_pad_template (element_class, srctempl);
112   gst_element_class_add_pad_template (element_class, sinktempl);
113
114   gst_caps_unref (sinkcaps);
115   gst_caps_unref (srccaps);
116
117   klass->in_plugin = in_plugin;
118   klass->srctempl = srctempl;
119   klass->sinktempl = sinktempl;
120 }
121
122 static void
123 gst_ffmpegauddec_class_init (GstFFMpegAudDecClass * klass)
124 {
125   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
126   GstAudioDecoderClass *gstaudiodecoder_class = GST_AUDIO_DECODER_CLASS (klass);
127
128   parent_class = g_type_class_peek_parent (klass);
129
130   gobject_class->finalize = gst_ffmpegauddec_finalize;
131
132   gstaudiodecoder_class->start = GST_DEBUG_FUNCPTR (gst_ffmpegauddec_start);
133   gstaudiodecoder_class->stop = GST_DEBUG_FUNCPTR (gst_ffmpegauddec_stop);
134   gstaudiodecoder_class->set_format =
135       GST_DEBUG_FUNCPTR (gst_ffmpegauddec_set_format);
136   gstaudiodecoder_class->handle_frame =
137       GST_DEBUG_FUNCPTR (gst_ffmpegauddec_handle_frame);
138   gstaudiodecoder_class->flush = GST_DEBUG_FUNCPTR (gst_ffmpegauddec_flush);
139   gstaudiodecoder_class->propose_allocation =
140       GST_DEBUG_FUNCPTR (gst_ffmpegauddec_propose_allocation);
141
142   GST_DEBUG_CATEGORY_GET (GST_CAT_PERFORMANCE, "GST_PERFORMANCE");
143 }
144
145 static void
146 gst_ffmpegauddec_init (GstFFMpegAudDec * ffmpegdec)
147 {
148   GstFFMpegAudDecClass *klass =
149       (GstFFMpegAudDecClass *) G_OBJECT_GET_CLASS (ffmpegdec);
150
151   /* some ffmpeg data */
152   ffmpegdec->context = avcodec_alloc_context3 (klass->in_plugin);
153   ffmpegdec->context->opaque = ffmpegdec;
154   ffmpegdec->opened = FALSE;
155
156   ffmpegdec->frame = av_frame_alloc ();
157
158   GST_PAD_SET_ACCEPT_TEMPLATE (GST_AUDIO_DECODER_SINK_PAD (ffmpegdec));
159   gst_audio_decoder_set_use_default_pad_acceptcaps (GST_AUDIO_DECODER_CAST
160       (ffmpegdec), TRUE);
161
162   gst_audio_decoder_set_drainable (GST_AUDIO_DECODER (ffmpegdec), TRUE);
163   gst_audio_decoder_set_needs_format (GST_AUDIO_DECODER (ffmpegdec), TRUE);
164 }
165
166 static void
167 gst_ffmpegauddec_finalize (GObject * object)
168 {
169   GstFFMpegAudDec *ffmpegdec = (GstFFMpegAudDec *) object;
170
171   av_frame_free (&ffmpegdec->frame);
172   avcodec_free_context (&ffmpegdec->context);
173
174   G_OBJECT_CLASS (parent_class)->finalize (object);
175 }
176
177 /* With LOCK */
178 static gboolean
179 gst_ffmpegauddec_close (GstFFMpegAudDec * ffmpegdec, gboolean reset)
180 {
181   GstFFMpegAudDecClass *oclass;
182
183   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
184
185   GST_LOG_OBJECT (ffmpegdec, "closing libav codec");
186
187   gst_caps_replace (&ffmpegdec->last_caps, NULL);
188
189   gst_ffmpeg_avcodec_close (ffmpegdec->context);
190   ffmpegdec->opened = FALSE;
191
192   av_freep (&ffmpegdec->context->extradata);
193
194   if (reset) {
195     avcodec_free_context (&ffmpegdec->context);
196     ffmpegdec->context = avcodec_alloc_context3 (oclass->in_plugin);
197     if (ffmpegdec->context == NULL) {
198       GST_DEBUG_OBJECT (ffmpegdec, "Failed to set context defaults");
199       return FALSE;
200     }
201     ffmpegdec->context->opaque = ffmpegdec;
202   }
203
204   return TRUE;
205 }
206
207 static gboolean
208 gst_ffmpegauddec_start (GstAudioDecoder * decoder)
209 {
210   GstFFMpegAudDec *ffmpegdec = (GstFFMpegAudDec *) decoder;
211   GstFFMpegAudDecClass *oclass;
212
213   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
214
215   GST_OBJECT_LOCK (ffmpegdec);
216   avcodec_free_context (&ffmpegdec->context);
217   ffmpegdec->context = avcodec_alloc_context3 (oclass->in_plugin);
218   if (ffmpegdec->context == NULL) {
219     GST_DEBUG_OBJECT (ffmpegdec, "Failed to set context defaults");
220     GST_OBJECT_UNLOCK (ffmpegdec);
221     return FALSE;
222   }
223   ffmpegdec->context->opaque = ffmpegdec;
224
225   /* FIXME: https://gitlab.freedesktop.org/gstreamer/gstreamer/-/issues/1474 */
226   if ((oclass->in_plugin->capabilities & AV_CODEC_CAP_DELAY) != 0
227       && (oclass->in_plugin->id == AV_CODEC_ID_WMAV1
228           || oclass->in_plugin->id == AV_CODEC_ID_WMAV2)) {
229     ffmpegdec->context->flags2 |= AV_CODEC_FLAG2_SKIP_MANUAL;
230   }
231
232   GST_OBJECT_UNLOCK (ffmpegdec);
233
234   return TRUE;
235 }
236
237 static gboolean
238 gst_ffmpegauddec_stop (GstAudioDecoder * decoder)
239 {
240   GstFFMpegAudDec *ffmpegdec = (GstFFMpegAudDec *) decoder;
241
242   GST_OBJECT_LOCK (ffmpegdec);
243   gst_ffmpegauddec_close (ffmpegdec, FALSE);
244   g_free (ffmpegdec->padded);
245   ffmpegdec->padded = NULL;
246   ffmpegdec->padded_size = 0;
247   GST_OBJECT_UNLOCK (ffmpegdec);
248   gst_audio_info_init (&ffmpegdec->info);
249   gst_caps_replace (&ffmpegdec->last_caps, NULL);
250
251   return TRUE;
252 }
253
254 /* with LOCK */
255 static gboolean
256 gst_ffmpegauddec_open (GstFFMpegAudDec * ffmpegdec)
257 {
258   GstFFMpegAudDecClass *oclass;
259
260   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
261
262   if (gst_ffmpeg_avcodec_open (ffmpegdec->context, oclass->in_plugin) < 0)
263     goto could_not_open;
264
265   ffmpegdec->opened = TRUE;
266
267   GST_LOG_OBJECT (ffmpegdec, "Opened libav codec %s, id %d",
268       oclass->in_plugin->name, oclass->in_plugin->id);
269
270   gst_audio_info_init (&ffmpegdec->info);
271
272   return TRUE;
273
274   /* ERRORS */
275 could_not_open:
276   {
277     gst_ffmpegauddec_close (ffmpegdec, TRUE);
278     GST_DEBUG_OBJECT (ffmpegdec, "avdec_%s: Failed to open libav codec",
279         oclass->in_plugin->name);
280     return FALSE;
281   }
282 }
283
284 static gboolean
285 gst_ffmpegauddec_propose_allocation (GstAudioDecoder * decoder,
286     GstQuery * query)
287 {
288   GstAllocationParams params;
289
290   gst_allocation_params_init (&params);
291   params.flags = GST_MEMORY_FLAG_ZERO_PADDED;
292   params.align = 15;
293   params.padding = AV_INPUT_BUFFER_PADDING_SIZE;
294   /* we would like to have some padding so that we don't have to
295    * memcpy. We don't suggest an allocator. */
296   gst_query_add_allocation_param (query, NULL, &params);
297
298   return GST_AUDIO_DECODER_CLASS (parent_class)->propose_allocation (decoder,
299       query);
300 }
301
302 static gboolean
303 gst_ffmpegauddec_set_format (GstAudioDecoder * decoder, GstCaps * caps)
304 {
305   GstFFMpegAudDec *ffmpegdec = (GstFFMpegAudDec *) decoder;
306   GstFFMpegAudDecClass *oclass;
307   gboolean ret = TRUE;
308
309   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
310
311   GST_DEBUG_OBJECT (ffmpegdec, "setcaps called");
312
313   GST_OBJECT_LOCK (ffmpegdec);
314
315   if (ffmpegdec->last_caps && gst_caps_is_equal (ffmpegdec->last_caps, caps)) {
316     GST_DEBUG_OBJECT (ffmpegdec, "same caps");
317     GST_OBJECT_UNLOCK (ffmpegdec);
318     return TRUE;
319   }
320
321   gst_caps_replace (&ffmpegdec->last_caps, caps);
322
323   /* close old session */
324   if (ffmpegdec->opened) {
325     GST_OBJECT_UNLOCK (ffmpegdec);
326     gst_ffmpegauddec_drain (ffmpegdec, FALSE);
327     GST_OBJECT_LOCK (ffmpegdec);
328     if (!gst_ffmpegauddec_close (ffmpegdec, TRUE)) {
329       GST_OBJECT_UNLOCK (ffmpegdec);
330       return FALSE;
331     }
332   }
333
334   /* get size and so */
335   gst_ffmpeg_caps_with_codecid (oclass->in_plugin->id,
336       oclass->in_plugin->type, caps, ffmpegdec->context);
337
338   /* workaround encoder bugs */
339   ffmpegdec->context->workaround_bugs |= FF_BUG_AUTODETECT;
340   ffmpegdec->context->err_recognition = 1;
341
342   /* open codec - we don't select an output pix_fmt yet,
343    * simply because we don't know! We only get it
344    * during playback... */
345   if (!gst_ffmpegauddec_open (ffmpegdec))
346     goto open_failed;
347
348 done:
349   GST_OBJECT_UNLOCK (ffmpegdec);
350
351   return ret;
352
353   /* ERRORS */
354 open_failed:
355   {
356     GST_DEBUG_OBJECT (ffmpegdec, "Failed to open");
357     ret = FALSE;
358     goto done;
359   }
360 }
361
362 static gboolean
363 settings_changed (GstFFMpegAudDec * ffmpegdec, AVFrame * frame)
364 {
365   GstAudioFormat format;
366   GstAudioLayout layout;
367   gint channels = av_get_channel_layout_nb_channels (frame->channel_layout);
368
369   if (channels == 0)
370     channels = frame->channels;
371
372   format = gst_ffmpeg_smpfmt_to_audioformat (frame->format, &layout);
373   if (format == GST_AUDIO_FORMAT_UNKNOWN)
374     return TRUE;
375
376   return !(ffmpegdec->info.rate == frame->sample_rate &&
377       ffmpegdec->info.channels == channels &&
378       ffmpegdec->info.finfo->format == format &&
379       ffmpegdec->info.layout == layout);
380 }
381
382 static gboolean
383 gst_ffmpegauddec_negotiate (GstFFMpegAudDec * ffmpegdec,
384     AVCodecContext * context, AVFrame * frame, gboolean force)
385 {
386   GstFFMpegAudDecClass *oclass;
387   GstAudioFormat format;
388   GstAudioLayout layout;
389   gint channels;
390   GstAudioChannelPosition pos[64] = { 0, };
391
392   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
393
394   format = gst_ffmpeg_smpfmt_to_audioformat (frame->format, &layout);
395   if (format == GST_AUDIO_FORMAT_UNKNOWN)
396     goto no_caps;
397   channels = av_get_channel_layout_nb_channels (frame->channel_layout);
398   if (channels == 0)
399     channels = frame->channels;
400   if (channels == 0)
401     goto no_caps;
402
403   if (!force && !settings_changed (ffmpegdec, frame))
404     return TRUE;
405
406   GST_DEBUG_OBJECT (ffmpegdec,
407       "Renegotiating audio from %dHz@%dchannels (%d, interleaved=%d) "
408       "to %dHz@%dchannels (%d, interleaved=%d)",
409       ffmpegdec->info.rate, ffmpegdec->info.channels,
410       ffmpegdec->info.finfo->format,
411       ffmpegdec->info.layout == GST_AUDIO_LAYOUT_INTERLEAVED,
412       frame->sample_rate, channels, format,
413       layout == GST_AUDIO_LAYOUT_INTERLEAVED);
414
415   gst_ffmpeg_channel_layout_to_gst (frame->channel_layout, channels, pos);
416   memcpy (ffmpegdec->ffmpeg_layout, pos,
417       sizeof (GstAudioChannelPosition) * channels);
418
419   /* Get GStreamer channel layout */
420   gst_audio_channel_positions_to_valid_order (pos, channels);
421   ffmpegdec->needs_reorder =
422       memcmp (pos, ffmpegdec->ffmpeg_layout, sizeof (pos[0]) * channels) != 0;
423   gst_audio_info_set_format (&ffmpegdec->info, format,
424       frame->sample_rate, channels, pos);
425   ffmpegdec->info.layout = layout;
426
427   if (!gst_audio_decoder_set_output_format (GST_AUDIO_DECODER (ffmpegdec),
428           &ffmpegdec->info))
429     goto caps_failed;
430
431   return TRUE;
432
433   /* ERRORS */
434 no_caps:
435   {
436 #ifdef HAVE_LIBAV_UNINSTALLED
437     /* using internal ffmpeg snapshot */
438     GST_ELEMENT_ERROR (ffmpegdec, CORE, NEGOTIATION,
439         ("Could not find GStreamer caps mapping for libav codec '%s'.",
440             oclass->in_plugin->name), (NULL));
441 #else
442     /* using external ffmpeg */
443     GST_ELEMENT_ERROR (ffmpegdec, CORE, NEGOTIATION,
444         ("Could not find GStreamer caps mapping for libav codec '%s', and "
445             "you are using an external libavcodec. This is most likely due to "
446             "a packaging problem and/or libavcodec having been upgraded to a "
447             "version that is not compatible with this version of "
448             "gstreamer-libav. Make sure your gstreamer-libav and libavcodec "
449             "packages come from the same source/repository.",
450             oclass->in_plugin->name), (NULL));
451 #endif
452     return FALSE;
453   }
454 caps_failed:
455   {
456     GST_ELEMENT_ERROR (ffmpegdec, CORE, NEGOTIATION, (NULL),
457         ("Could not set caps for libav decoder (%s), not fixed?",
458             oclass->in_plugin->name));
459     memset (&ffmpegdec->info, 0, sizeof (ffmpegdec->info));
460
461     return FALSE;
462   }
463 }
464
465 static void
466 gst_avpacket_init (AVPacket * packet, guint8 * data, guint size)
467 {
468   memset (packet, 0, sizeof (AVPacket));
469   packet->data = data;
470   packet->size = size;
471 }
472
473 /*
474  * Returns: whether a frame was decoded
475  */
476 static gboolean
477 gst_ffmpegauddec_audio_frame (GstFFMpegAudDec * ffmpegdec,
478     AVCodec * in_plugin, GstBuffer ** outbuf, GstFlowReturn * ret,
479     gboolean * need_more_data)
480 {
481   gboolean got_frame = FALSE;
482   gint res;
483
484   res = avcodec_receive_frame (ffmpegdec->context, ffmpegdec->frame);
485
486   if (res >= 0) {
487     gint nsamples, channels, byte_per_sample;
488     gsize output_size;
489     gboolean planar;
490
491     if (!gst_ffmpegauddec_negotiate (ffmpegdec, ffmpegdec->context,
492             ffmpegdec->frame, FALSE)) {
493       *outbuf = NULL;
494       *ret = GST_FLOW_NOT_NEGOTIATED;
495       goto beach;
496     }
497
498     got_frame = TRUE;
499
500     channels = ffmpegdec->info.channels;
501     nsamples = ffmpegdec->frame->nb_samples;
502     byte_per_sample = ffmpegdec->info.finfo->width / 8;
503     planar = av_sample_fmt_is_planar (ffmpegdec->frame->format);
504
505     g_return_val_if_fail (ffmpegdec->info.layout == (planar ?
506             GST_AUDIO_LAYOUT_NON_INTERLEAVED : GST_AUDIO_LAYOUT_INTERLEAVED),
507         GST_FLOW_NOT_NEGOTIATED);
508
509     GST_DEBUG_OBJECT (ffmpegdec, "Creating output buffer");
510
511     /* ffmpegdec->frame->linesize[0] might contain padding, allocate only what's needed */
512     output_size = nsamples * byte_per_sample * channels;
513
514     *outbuf =
515         gst_audio_decoder_allocate_output_buffer (GST_AUDIO_DECODER
516         (ffmpegdec), output_size);
517
518     if (planar) {
519       gint i;
520       GstAudioMeta *meta;
521
522       meta = gst_buffer_add_audio_meta (*outbuf, &ffmpegdec->info, nsamples,
523           NULL);
524
525       for (i = 0; i < channels; i++) {
526         gst_buffer_fill (*outbuf, meta->offsets[i],
527             ffmpegdec->frame->extended_data[i], nsamples * byte_per_sample);
528       }
529     } else {
530       gst_buffer_fill (*outbuf, 0, ffmpegdec->frame->data[0], output_size);
531     }
532
533     GST_DEBUG_OBJECT (ffmpegdec, "Buffer created. Size: %" G_GSIZE_FORMAT,
534         output_size);
535
536     /* Reorder channels to the GStreamer channel order */
537     if (ffmpegdec->needs_reorder) {
538       *outbuf = gst_buffer_make_writable (*outbuf);
539       gst_audio_buffer_reorder_channels (*outbuf, ffmpegdec->info.finfo->format,
540           ffmpegdec->info.channels, ffmpegdec->ffmpeg_layout,
541           ffmpegdec->info.position);
542     }
543
544     /* Mark corrupted frames as corrupted */
545     if (ffmpegdec->frame->flags & AV_FRAME_FLAG_CORRUPT)
546       GST_BUFFER_FLAG_SET (*outbuf, GST_BUFFER_FLAG_CORRUPTED);
547   } else if (res == AVERROR (EAGAIN)) {
548     GST_DEBUG_OBJECT (ffmpegdec, "Need more data");
549     *outbuf = NULL;
550     *need_more_data = TRUE;
551   } else if (res == AVERROR_EOF) {
552     *ret = GST_FLOW_EOS;
553     GST_DEBUG_OBJECT (ffmpegdec, "Context was entirely flushed");
554   } else if (res < 0) {
555     GST_AUDIO_DECODER_ERROR (ffmpegdec, 1, STREAM, DECODE, (NULL),
556         ("Audio decoding error"), *ret);
557   }
558
559 beach:
560   av_frame_unref (ffmpegdec->frame);
561   GST_DEBUG_OBJECT (ffmpegdec, "return flow %s, out %p, got_frame %d",
562       gst_flow_get_name (*ret), *outbuf, got_frame);
563   return got_frame;
564 }
565
566 /*
567  * Returns: whether a frame was decoded
568  */
569 static gboolean
570 gst_ffmpegauddec_frame (GstFFMpegAudDec * ffmpegdec, GstFlowReturn * ret,
571     gboolean * need_more_data)
572 {
573   GstFFMpegAudDecClass *oclass;
574   GstBuffer *outbuf = NULL;
575   gboolean got_frame = FALSE;
576
577   if (G_UNLIKELY (ffmpegdec->context->codec == NULL))
578     goto no_codec;
579
580   *ret = GST_FLOW_OK;
581   ffmpegdec->context->frame_number++;
582
583   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
584
585   got_frame =
586       gst_ffmpegauddec_audio_frame (ffmpegdec, oclass->in_plugin, &outbuf, ret,
587       need_more_data);
588
589   if (outbuf) {
590     GST_LOG_OBJECT (ffmpegdec, "Decoded data, buffer %" GST_PTR_FORMAT, outbuf);
591     *ret =
592         gst_audio_decoder_finish_subframe (GST_AUDIO_DECODER_CAST (ffmpegdec),
593         outbuf);
594   } else {
595     GST_DEBUG_OBJECT (ffmpegdec, "We didn't get a decoded buffer");
596   }
597
598 beach:
599   return got_frame;
600
601   /* ERRORS */
602 no_codec:
603   {
604     GST_ERROR_OBJECT (ffmpegdec, "no codec context");
605     goto beach;
606   }
607 }
608
609 static GstFlowReturn
610 gst_ffmpegauddec_drain (GstFFMpegAudDec * ffmpegdec, gboolean force)
611 {
612   GstFlowReturn ret = GST_FLOW_OK;
613   gboolean got_any_frames = FALSE;
614   gboolean need_more_data = FALSE;
615   gboolean got_frame;
616
617   if (avcodec_send_packet (ffmpegdec->context, NULL))
618     goto send_packet_failed;
619
620   /* FIXME: https://gitlab.freedesktop.org/gstreamer/gstreamer/-/issues/1474 */
621   if (!(ffmpegdec->context->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
622     do {
623       got_frame = gst_ffmpegauddec_frame (ffmpegdec, &ret, &need_more_data);
624       if (got_frame)
625         got_any_frames = TRUE;
626     } while (got_frame && !need_more_data);
627   }
628   avcodec_flush_buffers (ffmpegdec->context);
629
630   /* FFMpeg will return AVERROR_EOF if it's internal was fully drained
631    * then we are translating it to GST_FLOW_EOS. However, because this behavior
632    * is fully internal stuff of this implementation and gstaudiodecoder
633    * baseclass doesn't convert this GST_FLOW_EOS to GST_FLOW_OK,
634    * convert this flow returned here */
635   if (ret == GST_FLOW_EOS)
636     ret = GST_FLOW_OK;
637
638   if (got_any_frames || force) {
639     GstFlowReturn new_ret =
640         gst_audio_decoder_finish_frame (GST_AUDIO_DECODER (ffmpegdec), NULL, 1);
641
642     if (ret == GST_FLOW_OK)
643       ret = new_ret;
644   }
645
646 done:
647   return ret;
648
649 send_packet_failed:
650   GST_WARNING_OBJECT (ffmpegdec, "send packet failed, could not drain decoder");
651   goto done;
652 }
653
654 static void
655 gst_ffmpegauddec_flush (GstAudioDecoder * decoder, gboolean hard)
656 {
657   GstFFMpegAudDec *ffmpegdec = (GstFFMpegAudDec *) decoder;
658
659   if (ffmpegdec->opened) {
660     avcodec_flush_buffers (ffmpegdec->context);
661   }
662 }
663
664 static GstFlowReturn
665 gst_ffmpegauddec_handle_frame (GstAudioDecoder * decoder, GstBuffer * inbuf)
666 {
667   GstFFMpegAudDec *ffmpegdec;
668   GstFFMpegAudDecClass *oclass;
669   guint8 *data;
670   GstMapInfo map;
671   gint size;
672   gboolean got_any_frames = FALSE;
673   gboolean got_frame;
674   GstFlowReturn ret = GST_FLOW_OK;
675   gboolean is_header;
676   AVPacket packet;
677   GstAudioClippingMeta *clipping_meta = NULL;
678   guint32 num_clipped_samples = 0;
679   gboolean fully_clipped = FALSE;
680   gboolean need_more_data = FALSE;
681
682   ffmpegdec = (GstFFMpegAudDec *) decoder;
683
684   if (G_UNLIKELY (!ffmpegdec->opened))
685     goto not_negotiated;
686
687   if (inbuf == NULL) {
688     return gst_ffmpegauddec_drain (ffmpegdec, FALSE);
689   }
690
691   inbuf = gst_buffer_ref (inbuf);
692   is_header = GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_HEADER);
693
694   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
695
696   GST_LOG_OBJECT (ffmpegdec,
697       "Received new data of size %" G_GSIZE_FORMAT ", offset:%" G_GUINT64_FORMAT
698       ", ts:%" GST_TIME_FORMAT ", dur:%" GST_TIME_FORMAT,
699       gst_buffer_get_size (inbuf), GST_BUFFER_OFFSET (inbuf),
700       GST_TIME_ARGS (GST_BUFFER_PTS (inbuf)),
701       GST_TIME_ARGS (GST_BUFFER_DURATION (inbuf)));
702
703   /* workarounds, functions write to buffers:
704    *  libavcodec/svq1.c:svq1_decode_frame writes to the given buffer.
705    *  libavcodec/svq3.c:svq3_decode_slice_header too.
706    * ffmpeg devs know about it and will fix it (they said). */
707   if (oclass->in_plugin->id == AV_CODEC_ID_SVQ1 ||
708       oclass->in_plugin->id == AV_CODEC_ID_SVQ3) {
709     inbuf = gst_buffer_make_writable (inbuf);
710   }
711
712   /* mpegaudioparse is setting buffer flags for the Xing/LAME header. This
713    * should not be passed to the decoder as it results in unnecessary silence
714    * samples to be output */
715   if (oclass->in_plugin->id == AV_CODEC_ID_MP3 &&
716       GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_DECODE_ONLY) &&
717       GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_DROPPABLE)) {
718     gst_buffer_unref (inbuf);
719     return gst_audio_decoder_finish_frame (decoder, NULL, 1);
720   }
721
722   clipping_meta = gst_buffer_get_audio_clipping_meta (inbuf);
723
724   gst_buffer_map (inbuf, &map, GST_MAP_READ);
725
726   data = map.data;
727   size = map.size;
728
729   if (size > 0 && (!GST_MEMORY_IS_ZERO_PADDED (map.memory)
730           || (map.maxsize - map.size) < AV_INPUT_BUFFER_PADDING_SIZE)) {
731     /* add padding */
732     if (ffmpegdec->padded_size < size + AV_INPUT_BUFFER_PADDING_SIZE) {
733       ffmpegdec->padded_size = size + AV_INPUT_BUFFER_PADDING_SIZE;
734       ffmpegdec->padded = g_realloc (ffmpegdec->padded, ffmpegdec->padded_size);
735       GST_LOG_OBJECT (ffmpegdec, "resized padding buffer to %d",
736           ffmpegdec->padded_size);
737     }
738     GST_CAT_TRACE_OBJECT (GST_CAT_PERFORMANCE, ffmpegdec,
739         "Copy input to add padding");
740     memcpy (ffmpegdec->padded, data, size);
741     memset (ffmpegdec->padded + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
742
743     data = ffmpegdec->padded;
744   }
745
746   gst_avpacket_init (&packet, data, size);
747
748   if (!packet.size)
749     goto unmap;
750
751   if (clipping_meta != NULL) {
752     if (clipping_meta->format == GST_FORMAT_DEFAULT) {
753       uint8_t *p = av_packet_new_side_data (&packet, AV_PKT_DATA_SKIP_SAMPLES,
754           10);
755       if (p != NULL) {
756         GstByteWriter writer;
757         guint32 start = clipping_meta->start;
758         guint32 end = clipping_meta->end;
759
760         num_clipped_samples = start + end;
761
762         gst_byte_writer_init_with_data (&writer, p, 10, FALSE);
763         gst_byte_writer_put_uint32_le (&writer, start);
764         gst_byte_writer_put_uint32_le (&writer, end);
765         GST_LOG_OBJECT (ffmpegdec, "buffer has clipping metadata; added skip "
766             "side data to avpacket with start %u and end %u", start, end);
767       }
768     } else {
769       GST_WARNING_OBJECT (ffmpegdec,
770           "buffer has clipping metadata in unsupported format %s",
771           gst_format_get_name (clipping_meta->format));
772     }
773   }
774
775   if (avcodec_send_packet (ffmpegdec->context, &packet) < 0) {
776     av_packet_free_side_data (&packet);
777     goto send_packet_failed;
778   }
779   av_packet_free_side_data (&packet);
780
781   do {
782     /* decode a frame of audio now */
783     got_frame = gst_ffmpegauddec_frame (ffmpegdec, &ret, &need_more_data);
784
785     if (got_frame)
786       got_any_frames = TRUE;
787
788     if (ret != GST_FLOW_OK) {
789       GST_LOG_OBJECT (ffmpegdec, "breaking because of flow ret %s",
790           gst_flow_get_name (ret));
791       /* bad flow return, make sure we discard all data and exit */
792       break;
793     }
794   } while (got_frame && !need_more_data);
795
796   /* The frame was fully clipped if we have samples to be clipped and
797    * it's either more than the known fixed frame size, or the decoder returned
798    * that it needs more data (EAGAIN) and we didn't decode any frames at all.
799    */
800   fully_clipped = (clipping_meta != NULL && num_clipped_samples > 0)
801       && ((ffmpegdec->context->frame_size != 0
802           && num_clipped_samples >= ffmpegdec->context->frame_size)
803       || (need_more_data && !got_any_frames));
804
805   if (is_header || got_any_frames || fully_clipped) {
806     /* Even if previous return wasn't GST_FLOW_OK, we need to call
807      * _finish_frame() since baseclass is expecting that _finish_frame()
808      * is followed by _finish_subframe()
809      */
810     GstFlowReturn new_ret =
811         gst_audio_decoder_finish_frame (GST_AUDIO_DECODER (ffmpegdec), NULL, 1);
812
813     /* Only override the flow return value if previously did have a GST_FLOW_OK.
814      * Failure to do this would result in skipping downstream issues caught in
815      * earlier steps. */
816     if (ret == GST_FLOW_OK)
817       ret = new_ret;
818   }
819
820 unmap:
821   gst_buffer_unmap (inbuf, &map);
822   gst_buffer_unref (inbuf);
823
824 done:
825   return ret;
826
827   /* ERRORS */
828 not_negotiated:
829   {
830     oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
831     GST_ELEMENT_ERROR (ffmpegdec, CORE, NEGOTIATION, (NULL),
832         ("avdec_%s: input format was not set before data start",
833             oclass->in_plugin->name));
834     ret = GST_FLOW_NOT_NEGOTIATED;
835     goto done;
836   }
837
838 send_packet_failed:
839   {
840     GST_AUDIO_DECODER_ERROR (ffmpegdec, 1, STREAM, DECODE, (NULL),
841         ("Audio decoding error"), ret);
842
843     if (ret == GST_FLOW_OK) {
844       /* Even if ffmpeg was not able to decode current audio frame,
845        * we should call gst_audio_decoder_finish_frame() so that baseclass
846        * can clear its internal status and can respect timestamp of later
847        * incoming buffers */
848       ret = gst_ffmpegauddec_drain (ffmpegdec, TRUE);
849     }
850     goto unmap;
851   }
852 }
853
854 gboolean
855 gst_ffmpegauddec_register (GstPlugin * plugin)
856 {
857   GTypeInfo typeinfo = {
858     sizeof (GstFFMpegAudDecClass),
859     (GBaseInitFunc) gst_ffmpegauddec_base_init,
860     NULL,
861     (GClassInitFunc) gst_ffmpegauddec_class_init,
862     NULL,
863     NULL,
864     sizeof (GstFFMpegAudDec),
865     0,
866     (GInstanceInitFunc) gst_ffmpegauddec_init,
867   };
868   GType type;
869   AVCodec *in_plugin;
870   void *i = 0;
871   gint rank;
872
873   GST_LOG ("Registering decoders");
874
875   while ((in_plugin = (AVCodec *) av_codec_iterate (&i))) {
876     gchar *type_name;
877
878     /* only decoders */
879     if (!av_codec_is_decoder (in_plugin)
880         || in_plugin->type != AVMEDIA_TYPE_AUDIO) {
881       continue;
882     }
883
884     /* no quasi codecs, please */
885     if (in_plugin->id == AV_CODEC_ID_PCM_S16LE_PLANAR ||
886         (in_plugin->id >= AV_CODEC_ID_PCM_S16LE &&
887             in_plugin->id <= AV_CODEC_ID_PCM_BLURAY) ||
888         (in_plugin->id >= AV_CODEC_ID_PCM_S8_PLANAR &&
889             in_plugin->id <= AV_CODEC_ID_PCM_F24LE))
890       continue;
891
892     /* No decoders depending on external libraries (we don't build them, but
893      * people who build against an external ffmpeg might have them.
894      * We have native gstreamer plugins for all of those libraries anyway. */
895     if (!strncmp (in_plugin->name, "lib", 3)) {
896       GST_DEBUG
897           ("Not using external library decoder %s. Use the gstreamer-native ones instead.",
898           in_plugin->name);
899       continue;
900     }
901
902     GST_DEBUG ("Trying plugin %s [%s]", in_plugin->name, in_plugin->long_name);
903
904     /* no codecs for which we're GUARANTEED to have better alternatives */
905     /* MP1 : Use MP3 for decoding */
906     /* MP2 : Use MP3 for decoding */
907     /* Theora: Use libtheora based theoradec */
908     if (!strcmp (in_plugin->name, "vorbis") ||
909         !strcmp (in_plugin->name, "wavpack") ||
910         !strcmp (in_plugin->name, "mp1") ||
911         !strcmp (in_plugin->name, "mp2") ||
912         !strcmp (in_plugin->name, "libfaad") ||
913         !strcmp (in_plugin->name, "mpeg4aac") ||
914         !strcmp (in_plugin->name, "ass") ||
915         !strcmp (in_plugin->name, "srt") ||
916         !strcmp (in_plugin->name, "pgssub") ||
917         !strcmp (in_plugin->name, "dvdsub") ||
918         !strcmp (in_plugin->name, "dvbsub")) {
919       GST_LOG ("Ignoring decoder %s", in_plugin->name);
920       continue;
921     }
922
923     /* construct the type */
924     type_name = g_strdup_printf ("avdec_%s", in_plugin->name);
925     g_strdelimit (type_name, ".,|-<> ", '_');
926
927     type = g_type_from_name (type_name);
928
929     if (!type) {
930       /* create the gtype now */
931       type =
932           g_type_register_static (GST_TYPE_AUDIO_DECODER, type_name, &typeinfo,
933           0);
934       g_type_set_qdata (type, GST_FFDEC_PARAMS_QDATA, (gpointer) in_plugin);
935     }
936
937     /* (Ronald) MPEG-4 gets a higher priority because it has been well-
938      * tested and by far outperforms divxdec/xviddec - so we prefer it.
939      * msmpeg4v3 same, as it outperforms divxdec for divx3 playback.
940      * VC1/WMV3 are not working and thus unpreferred for now. */
941     switch (in_plugin->id) {
942       case AV_CODEC_ID_RA_144:
943       case AV_CODEC_ID_RA_288:
944       case AV_CODEC_ID_COOK:
945       case AV_CODEC_ID_AAC:
946         rank = GST_RANK_PRIMARY;
947         break;
948         /* SIPR: decoder should have a higher rank than realaudiodec.
949          */
950       case AV_CODEC_ID_SIPR:
951         rank = GST_RANK_SECONDARY;
952         break;
953       default:
954         rank = GST_RANK_MARGINAL;
955         break;
956     }
957     if (!gst_element_register (plugin, type_name, rank, type)) {
958       g_warning ("Failed to register %s", type_name);
959       g_free (type_name);
960       return FALSE;
961     }
962
963     g_free (type_name);
964   }
965
966   GST_LOG ("Finished Registering decoders");
967
968   return TRUE;
969 }