webrtc/nice: Support domain name as connection-address of ICE candidate
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / ext / fdkaac / gstfdkaacenc.c
1 /*
2  * Copyright (C) 2016 Sebastian Dröge <sebastian@centricular.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include "gstfdkaac.h"
25 #include "gstfdkaacenc.h"
26
27 #include <gst/pbutils/pbutils.h>
28
29 #include <string.h>
30
31 /* TODO:
32  * - Add support for other AOT / profiles
33  * - Signal encoder delay
34  * - LOAS / LATM support
35  */
36
37 enum
38 {
39   PROP_0,
40   PROP_AFTERBURNER,
41   PROP_BITRATE,
42   PROP_PEAK_BITRATE,
43   PROP_RATE_CONTROL,
44   PROP_VBR_PRESET,
45 };
46
47 #define DEFAULT_BITRATE (0)
48 #define DEFAULT_PEAK_BITRATE (0)
49 #define DEFAULT_RATE_CONTROL (GST_FDK_AAC_RATE_CONTROL_CONSTANT_BITRATE)
50 #define DEFAULT_VBR_PRESET (GST_FDK_AAC_VBR_PRESET_MEDIUM)
51
52 #define SAMPLE_RATES " 8000, " \
53                     "11025, " \
54                     "12000, " \
55                     "16000, " \
56                     "22050, " \
57                     "24000, " \
58                     "32000, " \
59                     "44100, " \
60                     "48000, " \
61                     "64000, " \
62                     "88200, " \
63                     "96000"
64
65 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
66     GST_PAD_SINK,
67     GST_PAD_ALWAYS,
68     GST_STATIC_CAPS ("audio/x-raw, "
69         "format = (string) " GST_AUDIO_NE (S16) ", "
70         "layout = (string) interleaved, "
71         "rate = (int) { " SAMPLE_RATES " }, "
72         "channels = (int) {1, 2, 3, 4, 5, 6, 8}")
73     );
74
75 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
76     GST_PAD_SRC,
77     GST_PAD_ALWAYS,
78     GST_STATIC_CAPS ("audio/mpeg, "
79         "mpegversion = (int) 4, "
80         "rate = (int) { " SAMPLE_RATES " }, "
81         "channels = (int) {1, 2, 3, 4, 5, 6, 8}, "
82         "stream-format = (string) { adts, adif, raw }, "
83         "profile = (string) { lc, he-aac-v1, he-aac-v2, ld }, "
84         "framed = (boolean) true")
85     );
86
87 GST_DEBUG_CATEGORY_STATIC (gst_fdkaacenc_debug);
88 #define GST_CAT_DEFAULT gst_fdkaacenc_debug
89
90 static void gst_fdkaacenc_set_property (GObject * object, guint prop_id,
91     const GValue * value, GParamSpec * pspec);
92 static void gst_fdkaacenc_get_property (GObject * object, guint prop_id,
93     GValue * value, GParamSpec * pspec);
94 static gboolean gst_fdkaacenc_start (GstAudioEncoder * enc);
95 static gboolean gst_fdkaacenc_stop (GstAudioEncoder * enc);
96 static gboolean gst_fdkaacenc_set_format (GstAudioEncoder * enc,
97     GstAudioInfo * info);
98 static GstFlowReturn gst_fdkaacenc_handle_frame (GstAudioEncoder * enc,
99     GstBuffer * in_buf);
100 static GstCaps *gst_fdkaacenc_get_caps (GstAudioEncoder * enc,
101     GstCaps * filter);
102 static void gst_fdkaacenc_flush (GstAudioEncoder * enc);
103
104 G_DEFINE_TYPE (GstFdkAacEnc, gst_fdkaacenc, GST_TYPE_AUDIO_ENCODER);
105 GST_ELEMENT_REGISTER_DEFINE (fdkaacenc, "fdkaacenc", GST_RANK_PRIMARY,
106     GST_TYPE_FDKAACENC);
107
108 #define GST_FDK_AAC_VBR_PRESET (gst_fdk_aac_vbr_preset_get_type ())
109 static GType
110 gst_fdk_aac_vbr_preset_get_type (void)
111 {
112   static GType fdk_aac_vbr_preset_type = 0;
113   static const GEnumValue vbr_preset_types[] = {
114     {GST_FDK_AAC_VBR_PRESET_VERY_LOW, "Very Low Variable Bitrate", "very-low"},
115     {GST_FDK_AAC_VBR_PRESET_LOW, "Low Variable Bitrate", "low"},
116     {GST_FDK_AAC_VBR_PRESET_MEDIUM, "Medium Variable Bitrate", "medium"},
117     {GST_FDK_AAC_VBR_PRESET_HIGH, "High Variable Bitrate", "high"},
118     {GST_FDK_AAC_VBR_PRESET_VERY_HIGH, "Very High Variable Bitrate",
119         "very-high"},
120     {0, NULL, NULL}
121   };
122
123   if (!fdk_aac_vbr_preset_type)
124     fdk_aac_vbr_preset_type =
125         g_enum_register_static ("GstFdkAacVbrPreset", vbr_preset_types);
126
127   return fdk_aac_vbr_preset_type;
128 }
129
130 #define GST_FDK_AAC_RATE_CONTROL (gst_fdk_aac_rate_control_get_type ())
131 static GType
132 gst_fdk_aac_rate_control_get_type (void)
133 {
134   static GType fdk_aac_rate_control_type = 0;
135   static const GEnumValue rate_control_types[] = {
136     {GST_FDK_AAC_RATE_CONTROL_CONSTANT_BITRATE, "Constant Bitrate", "cbr"},
137     {GST_FDK_AAC_RATE_CONTROL_VARIABLE_BITRATE, "Variable Bitrate", "vbr"},
138     {0, NULL, NULL}
139   };
140
141   if (!fdk_aac_rate_control_type)
142     fdk_aac_rate_control_type =
143         g_enum_register_static ("GstFdkAacRateControl", rate_control_types);
144
145   return fdk_aac_rate_control_type;
146 }
147
148 static void
149 gst_fdkaacenc_set_property (GObject * object, guint prop_id,
150     const GValue * value, GParamSpec * pspec)
151 {
152   GstFdkAacEnc *self = GST_FDKAACENC (object);
153
154   switch (prop_id) {
155     case PROP_BITRATE:
156       self->bitrate = g_value_get_int (value);
157       break;
158     case PROP_AFTERBURNER:
159       self->afterburner = g_value_get_boolean (value);
160       break;
161     case PROP_PEAK_BITRATE:
162       self->peak_bitrate = g_value_get_int (value);
163       break;
164     case PROP_RATE_CONTROL:
165       self->rate_control = g_value_get_enum (value);
166       break;
167     case PROP_VBR_PRESET:
168       self->vbr_preset = g_value_get_enum (value);
169       break;
170     default:
171       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
172       break;
173   }
174   return;
175 }
176
177 static void
178 gst_fdkaacenc_get_property (GObject * object, guint prop_id,
179     GValue * value, GParamSpec * pspec)
180 {
181   GstFdkAacEnc *self = GST_FDKAACENC (object);
182
183   switch (prop_id) {
184     case PROP_BITRATE:
185       g_value_set_int (value, self->bitrate);
186       break;
187     case PROP_AFTERBURNER:
188       g_value_set_boolean (value, self->afterburner);
189       break;
190     case PROP_PEAK_BITRATE:
191       g_value_set_int (value, self->peak_bitrate);
192       break;
193     case PROP_RATE_CONTROL:
194       g_value_set_enum (value, self->rate_control);
195       break;
196     case PROP_VBR_PRESET:
197       g_value_set_enum (value, self->vbr_preset);
198       break;
199     default:
200       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
201       break;
202   }
203   return;
204 }
205
206 static gboolean
207 gst_fdkaacenc_start (GstAudioEncoder * enc)
208 {
209   GstFdkAacEnc *self = GST_FDKAACENC (enc);
210
211   GST_DEBUG_OBJECT (self, "start");
212
213   return TRUE;
214 }
215
216 static gboolean
217 gst_fdkaacenc_stop (GstAudioEncoder * enc)
218 {
219   GstFdkAacEnc *self = GST_FDKAACENC (enc);
220
221   GST_DEBUG_OBJECT (self, "stop");
222
223   if (self->enc) {
224     aacEncClose (&self->enc);
225     self->enc = NULL;
226   }
227
228   self->is_drained = TRUE;
229   return TRUE;
230 }
231
232 static GstCaps *
233 gst_fdkaacenc_get_caps (GstAudioEncoder * enc, GstCaps * filter)
234 {
235   const GstFdkAacChannelLayout *layout;
236   GstCaps *res, *caps, *allowed_caps;
237   gboolean allow_mono = TRUE;
238
239   allowed_caps = gst_pad_get_allowed_caps (GST_AUDIO_ENCODER_SRC_PAD (enc));
240   GST_DEBUG_OBJECT (enc, "allowed caps %" GST_PTR_FORMAT, allowed_caps);
241
242   /* We need at least 2 channels if Parametric Stereo is in use. */
243   if (allowed_caps && gst_caps_get_size (allowed_caps) > 0) {
244     GstStructure *s = gst_caps_get_structure (allowed_caps, 0);
245     const gchar *profile = NULL;
246
247     if ((profile = gst_structure_get_string (s, "profile"))
248         && strcmp (profile, "he-aac-v2") == 0) {
249       allow_mono = FALSE;
250     }
251   }
252   gst_clear_caps (&allowed_caps);
253
254   caps = gst_caps_new_empty ();
255
256   for (layout = channel_layouts; layout->channels; layout++) {
257     GstCaps *tmp;
258     gint channels = layout->channels;
259
260     if (channels == 1 && !allow_mono)
261       continue;
262
263     tmp = gst_caps_make_writable (gst_pad_get_pad_template_caps
264         (GST_AUDIO_ENCODER_SINK_PAD (enc)));
265
266     if (channels == 1) {
267       gst_caps_set_simple (tmp, "channels", G_TYPE_INT, channels, NULL);
268     } else {
269       guint64 channel_mask;
270       gst_audio_channel_positions_to_mask (layout->positions, channels, FALSE,
271           &channel_mask);
272       gst_caps_set_simple (tmp, "channels", G_TYPE_INT, channels,
273           "channel-mask", GST_TYPE_BITMASK, channel_mask, NULL);
274     }
275
276     gst_caps_append (caps, tmp);
277   }
278
279   res = gst_audio_encoder_proxy_getcaps (enc, caps, filter);
280   gst_caps_unref (caps);
281
282   return res;
283 }
284
285 static gboolean
286 gst_fdkaacenc_set_format (GstAudioEncoder * enc, GstAudioInfo * info)
287 {
288   GstFdkAacEnc *self = GST_FDKAACENC (enc);
289   gboolean ret = FALSE;
290   GstCaps *allowed_caps;
291   GstCaps *src_caps;
292   AACENC_ERROR err;
293   gint transmux = 0;
294   gint mpegversion = 4;
295   gint aot = AOT_AAC_LC;
296   const gchar *profile_str = "lc";
297   CHANNEL_MODE channel_mode;
298   AACENC_InfoStruct enc_info = { 0 };
299   gint bitrate, signaling_mode;
300   guint bitrate_mode;
301
302   if (self->enc && !self->is_drained) {
303     /* drain */
304     gst_fdkaacenc_handle_frame (enc, NULL);
305     aacEncClose (&self->enc);
306     self->is_drained = TRUE;
307   }
308
309   allowed_caps = gst_pad_get_allowed_caps (GST_AUDIO_ENCODER_SRC_PAD (self));
310
311   GST_DEBUG_OBJECT (self, "allowed caps: %" GST_PTR_FORMAT, allowed_caps);
312
313   if (allowed_caps && gst_caps_get_size (allowed_caps) > 0) {
314     GstStructure *s = gst_caps_get_structure (allowed_caps, 0);
315     const gchar *str = NULL;
316
317     if ((str = gst_structure_get_string (s, "stream-format"))) {
318       if (strcmp (str, "adts") == 0) {
319         GST_DEBUG_OBJECT (self, "use ADTS format for output");
320         transmux = 2;
321       } else if (strcmp (str, "adif") == 0) {
322         GST_DEBUG_OBJECT (self, "use ADIF format for output");
323         transmux = 1;
324       } else if (strcmp (str, "raw") == 0) {
325         GST_DEBUG_OBJECT (self, "use RAW format for output");
326         transmux = 0;
327       }
328     }
329
330     if ((str = gst_structure_get_string (s, "profile"))) {
331       if (strcmp (str, "lc") == 0) {
332         GST_DEBUG_OBJECT (self, "using AAC-LC profile for output");
333         aot = AOT_AAC_LC;
334         profile_str = "lc";
335       } else if (strcmp (str, "he-aac-v1") == 0) {
336         GST_DEBUG_OBJECT (self, "using SBR (HE-AACv1) profile for output");
337         aot = AOT_SBR;
338         profile_str = "he-aac-v1";
339       } else if (strcmp (str, "he-aac-v2") == 0) {
340         GST_DEBUG_OBJECT (self, "using PS (HE-AACv2) profile for output");
341         aot = AOT_PS;
342         profile_str = "he-aac-v2";
343       } else if (strcmp (str, "ld") == 0) {
344         GST_DEBUG_OBJECT (self, "using AAC-LD profile for output");
345         aot = AOT_ER_AAC_LD;
346         profile_str = "ld";
347       }
348     }
349
350     gst_structure_get_int (s, "mpegversion", &mpegversion);
351   }
352   if (allowed_caps)
353     gst_caps_unref (allowed_caps);
354
355   err = aacEncOpen (&self->enc, 0, GST_AUDIO_INFO_CHANNELS (info));
356   if (err != AACENC_OK) {
357     GST_ERROR_OBJECT (self, "Unable to open encoder: %d", err);
358     return FALSE;
359   }
360
361   if ((err = aacEncoder_SetParam (self->enc, AACENC_AOT, aot)) != AACENC_OK) {
362     GST_ERROR_OBJECT (self, "Unable to set AOT %d: %d", aot, err);
363     return FALSE;
364   }
365
366   /* Use explicit hierarchical signaling (2) with raw output stream-format
367    * and implicit signaling (0) with ADTS/ADIF */
368   if (transmux == 0)
369     signaling_mode = 2;
370   else
371     signaling_mode = 0;
372
373   if ((err = aacEncoder_SetParam (self->enc, AACENC_SIGNALING_MODE,
374               signaling_mode)) != AACENC_OK) {
375     GST_ERROR_OBJECT (self, "Unable to set signaling mode %d: %d",
376         signaling_mode, err);
377     return FALSE;
378   }
379
380   if ((err = aacEncoder_SetParam (self->enc, AACENC_SAMPLERATE,
381               GST_AUDIO_INFO_RATE (info))) != AACENC_OK) {
382     GST_ERROR_OBJECT (self, "Unable to set sample rate %d: %d",
383         GST_AUDIO_INFO_RATE (info), err);
384     return FALSE;
385   }
386
387   if (GST_AUDIO_INFO_CHANNELS (info) == 1) {
388     channel_mode = MODE_1;
389     self->need_reorder = FALSE;
390     self->aac_positions = NULL;
391   } else {
392     gint in_channels = GST_AUDIO_INFO_CHANNELS (info);
393     const GstAudioChannelPosition *in_positions =
394         &GST_AUDIO_INFO_POSITION (info, 0);
395     guint64 in_channel_mask;
396     const GstFdkAacChannelLayout *layout;
397
398     gst_audio_channel_positions_to_mask (in_positions, in_channels, FALSE,
399         &in_channel_mask);
400
401     for (layout = channel_layouts; layout->channels; layout++) {
402       gint channels = layout->channels;
403       const GstAudioChannelPosition *positions = layout->positions;
404       guint64 channel_mask;
405
406       if (channels != in_channels)
407         continue;
408
409       gst_audio_channel_positions_to_mask (positions, channels, FALSE,
410           &channel_mask);
411       if (channel_mask != in_channel_mask)
412         continue;
413
414       channel_mode = layout->mode;
415       self->need_reorder = memcmp (positions, in_positions,
416           channels * sizeof *positions) != 0;
417       self->aac_positions = positions;
418       break;
419     }
420
421     if (!layout->channels) {
422       GST_ERROR_OBJECT (self, "Couldn't find a valid channel layout");
423       return FALSE;
424     }
425   }
426
427   if ((err = aacEncoder_SetParam (self->enc, AACENC_CHANNELMODE,
428               channel_mode)) != AACENC_OK) {
429     GST_ERROR_OBJECT (self, "Unable to set channel mode %d: %d", channel_mode,
430         err);
431     return FALSE;
432   }
433
434   /* MPEG channel order */
435   if ((err = aacEncoder_SetParam (self->enc, AACENC_CHANNELORDER,
436               0)) != AACENC_OK) {
437     GST_ERROR_OBJECT (self, "Unable to set channel order %d: %d", channel_mode,
438         err);
439     return FALSE;
440   }
441
442   bitrate = self->bitrate;
443   /* See
444    * http://wiki.hydrogenaud.io/index.php?title=Fraunhofer_FDK_AAC#Recommended_Sampling_Rate_and_Bitrate_Combinations
445    */
446   if (bitrate == 0) {
447     if (GST_AUDIO_INFO_CHANNELS (info) == 1) {
448       if (GST_AUDIO_INFO_RATE (info) < 16000) {
449         bitrate = 8000;
450       } else if (GST_AUDIO_INFO_RATE (info) == 16000) {
451         bitrate = 16000;
452       } else if (GST_AUDIO_INFO_RATE (info) < 32000) {
453         bitrate = 24000;
454       } else if (GST_AUDIO_INFO_RATE (info) == 32000) {
455         bitrate = 32000;
456       } else if (GST_AUDIO_INFO_RATE (info) <= 44100) {
457         bitrate = 56000;
458       } else {
459         bitrate = 160000;
460       }
461     } else if (GST_AUDIO_INFO_CHANNELS (info) == 2) {
462       if (GST_AUDIO_INFO_RATE (info) < 16000) {
463         bitrate = 16000;
464       } else if (GST_AUDIO_INFO_RATE (info) == 16000) {
465         bitrate = 24000;
466       } else if (GST_AUDIO_INFO_RATE (info) < 22050) {
467         bitrate = 32000;
468       } else if (GST_AUDIO_INFO_RATE (info) < 32000) {
469         bitrate = 40000;
470       } else if (GST_AUDIO_INFO_RATE (info) == 32000) {
471         bitrate = 96000;
472       } else if (GST_AUDIO_INFO_RATE (info) <= 44100) {
473         bitrate = 112000;
474       } else {
475         bitrate = 320000;
476       }
477     } else {
478       /* 5, 5.1 */
479       if (GST_AUDIO_INFO_RATE (info) < 32000) {
480         bitrate = 160000;
481       } else if (GST_AUDIO_INFO_RATE (info) <= 44100) {
482         bitrate = 240000;
483       } else {
484         bitrate = 320000;
485       }
486     }
487   }
488
489   if ((err = aacEncoder_SetParam (self->enc, AACENC_TRANSMUX,
490               transmux)) != AACENC_OK) {
491     GST_ERROR_OBJECT (self, "Unable to set transmux %d: %d", transmux, err);
492     return FALSE;
493   }
494
495   if ((err = aacEncoder_SetParam (self->enc, AACENC_BITRATE,
496               bitrate)) != AACENC_OK) {
497     GST_ERROR_OBJECT (self, "Unable to set bitrate %d: %d", bitrate, err);
498     return FALSE;
499   }
500
501   if (self->rate_control == GST_FDK_AAC_RATE_CONTROL_CONSTANT_BITRATE) {
502     /*
503      * Note that the `bitrate` property is honoured only when using
504      * constant bit rate.
505      */
506     bitrate_mode = 0;           // Constant Bitrate
507   } else {
508     bitrate_mode = self->vbr_preset;
509   }
510
511   if ((err = aacEncoder_SetParam (self->enc, AACENC_BITRATEMODE,
512               bitrate_mode)) != AACENC_OK) {
513     GST_ERROR_OBJECT (self, "Unable to set bitrate mode %d: %d",
514         bitrate_mode, err);
515     return FALSE;
516   }
517
518   if (self->peak_bitrate) {
519     if ((err = aacEncoder_SetParam (self->enc, AACENC_PEAK_BITRATE,
520                 self->peak_bitrate)) != AACENC_OK) {
521       GST_ERROR_OBJECT (self, "Unable to set peak bitrate %d: %d",
522           self->peak_bitrate, err);
523       return FALSE;
524     }
525
526     GST_INFO_OBJECT (self, "Setting peak bitrate to %d", self->peak_bitrate);
527   }
528
529   if (self->afterburner) {
530     if ((err =
531             aacEncoder_SetParam (self->enc, AACENC_AFTERBURNER,
532                 1)) != AACENC_OK) {
533       GST_ERROR_OBJECT (self, "Could not enable afterburner: %d", err);
534       return FALSE;
535     }
536
537     GST_INFO_OBJECT (self, "Afterburner enabled");
538   }
539   if ((err = aacEncEncode (self->enc, NULL, NULL, NULL, NULL)) != AACENC_OK) {
540     GST_ERROR_OBJECT (self, "Unable to initialize encoder: %d", err);
541     return FALSE;
542   }
543
544   if ((err = aacEncInfo (self->enc, &enc_info)) != AACENC_OK) {
545     GST_ERROR_OBJECT (self, "Unable to get encoder info: %d", err);
546     return FALSE;
547   }
548
549   gst_audio_encoder_set_frame_max (enc, 1);
550   gst_audio_encoder_set_frame_samples_min (enc, enc_info.frameLength);
551   gst_audio_encoder_set_frame_samples_max (enc, enc_info.frameLength);
552   gst_audio_encoder_set_hard_min (enc, FALSE);
553   self->outbuf_size = enc_info.maxOutBufBytes;
554   self->samples_per_frame = enc_info.frameLength;
555
556   src_caps = gst_caps_new_simple ("audio/mpeg",
557       "mpegversion", G_TYPE_INT, mpegversion,
558       "channels", G_TYPE_INT, GST_AUDIO_INFO_CHANNELS (info),
559       "framed", G_TYPE_BOOLEAN, TRUE,
560       "rate", G_TYPE_INT, GST_AUDIO_INFO_RATE (info), NULL);
561
562   /* raw */
563   if (transmux == 0) {
564     GstBuffer *codec_data =
565         gst_buffer_new_memdup (enc_info.confBuf, enc_info.confSize);
566     gst_caps_set_simple (src_caps, "codec_data", GST_TYPE_BUFFER, codec_data,
567         "stream-format", G_TYPE_STRING, "raw", NULL);
568     gst_buffer_unref (codec_data);
569   } else if (transmux == 1) {
570     gst_caps_set_simple (src_caps, "stream-format", G_TYPE_STRING, "adif",
571         NULL);
572   } else if (transmux == 2) {
573     gst_caps_set_simple (src_caps, "stream-format", G_TYPE_STRING, "adts",
574         NULL);
575   } else {
576     g_assert_not_reached ();
577   }
578
579   gst_codec_utils_aac_caps_set_level_and_profile (src_caps, enc_info.confBuf,
580       enc_info.confSize);
581
582   /* The above only parses the "base" profile, which is always going to be LC.
583    * Set actual profile. */
584   gst_caps_set_simple (src_caps, "profile", G_TYPE_STRING, profile_str, NULL);
585
586   /* An AAC-LC-only decoder will not decode a stream that uses explicit
587    * hierarchical signaling */
588   if (signaling_mode == 2 && aot != AOT_AAC_LC) {
589     gst_structure_remove_field (gst_caps_get_structure (src_caps, 0),
590         "base-profile");
591   }
592
593   ret = gst_audio_encoder_set_output_format (enc, src_caps);
594   gst_caps_unref (src_caps);
595
596   return ret;
597 }
598
599 static GstFlowReturn
600 gst_fdkaacenc_handle_frame (GstAudioEncoder * enc, GstBuffer * inbuf)
601 {
602   GstFdkAacEnc *self = GST_FDKAACENC (enc);
603   GstFlowReturn ret = GST_FLOW_OK;
604   GstAudioInfo *info;
605   GstMapInfo imap, omap;
606   GstBuffer *outbuf;
607   AACENC_BufDesc in_desc = { 0 };
608   AACENC_BufDesc out_desc = { 0 };
609   AACENC_InArgs in_args = { 0 };
610   AACENC_OutArgs out_args = { 0 };
611   gint in_id = IN_AUDIO_DATA, out_id = OUT_BITSTREAM_DATA;
612   gint in_sizes, out_sizes;
613   gint in_el_sizes, out_el_sizes;
614   AACENC_ERROR err;
615
616   info = gst_audio_encoder_get_audio_info (enc);
617
618   if (inbuf) {
619     if (self->need_reorder) {
620       inbuf = gst_buffer_copy (inbuf);
621       gst_buffer_map (inbuf, &imap, GST_MAP_READWRITE);
622       gst_audio_reorder_channels (imap.data, imap.size,
623           GST_AUDIO_INFO_FORMAT (info), GST_AUDIO_INFO_CHANNELS (info),
624           &GST_AUDIO_INFO_POSITION (info, 0), self->aac_positions);
625     } else {
626       gst_buffer_map (inbuf, &imap, GST_MAP_READ);
627     }
628
629     in_args.numInSamples = imap.size / GST_AUDIO_INFO_BPS (info);
630
631     in_sizes = imap.size;
632     in_el_sizes = GST_AUDIO_INFO_BPS (info);
633     in_desc.numBufs = 1;
634   } else {
635     in_args.numInSamples = -1;
636
637     in_sizes = 0;
638     in_el_sizes = 0;
639     in_desc.numBufs = 0;
640   }
641   /* We unset is_drained even if there's no inbuf. Basically this is a
642    * workaround for aacEncEncode always producing 1024 bytes even without any
643    * input, thus messing up with the base class counting */
644   self->is_drained = FALSE;
645
646   in_desc.bufferIdentifiers = &in_id;
647   in_desc.bufs = (void *) &imap.data;
648   in_desc.bufSizes = &in_sizes;
649   in_desc.bufElSizes = &in_el_sizes;
650
651   outbuf = gst_audio_encoder_allocate_output_buffer (enc, self->outbuf_size);
652   if (!outbuf) {
653     ret = GST_FLOW_ERROR;
654     goto out;
655   }
656
657   gst_buffer_map (outbuf, &omap, GST_MAP_WRITE);
658   out_sizes = omap.size;
659   out_el_sizes = 1;
660   out_desc.bufferIdentifiers = &out_id;
661   out_desc.numBufs = 1;
662   out_desc.bufs = (void *) &omap.data;
663   out_desc.bufSizes = &out_sizes;
664   out_desc.bufElSizes = &out_el_sizes;
665
666   err = aacEncEncode (self->enc, &in_desc, &out_desc, &in_args, &out_args);
667   if (err == AACENC_ENCODE_EOF && !inbuf)
668     goto out;
669   else if (err != AACENC_OK) {
670     GST_ERROR_OBJECT (self, "Failed to encode data: %d", err);
671     ret = GST_FLOW_ERROR;
672     goto out;
673   }
674
675   if (inbuf) {
676     gst_buffer_unmap (inbuf, &imap);
677     if (self->need_reorder)
678       gst_buffer_unref (inbuf);
679     inbuf = NULL;
680   }
681
682   if (!out_args.numOutBytes)
683     goto out;
684
685   gst_buffer_unmap (outbuf, &omap);
686   gst_buffer_set_size (outbuf, out_args.numOutBytes);
687
688   ret = gst_audio_encoder_finish_frame (enc, outbuf, self->samples_per_frame);
689   outbuf = NULL;
690
691 out:
692   if (outbuf) {
693     gst_buffer_unmap (outbuf, &omap);
694     gst_buffer_unref (outbuf);
695   }
696   if (inbuf) {
697     gst_buffer_unmap (inbuf, &imap);
698     if (self->need_reorder)
699       gst_buffer_unref (inbuf);
700   }
701
702   return ret;
703 }
704
705 static void
706 gst_fdkaacenc_flush (GstAudioEncoder * enc)
707 {
708   GstFdkAacEnc *self = GST_FDKAACENC (enc);
709   GstAudioInfo *info = gst_audio_encoder_get_audio_info (enc);
710
711   aacEncClose (&self->enc);
712   self->enc = NULL;
713   self->is_drained = TRUE;
714
715   if (GST_AUDIO_INFO_IS_VALID (info))
716     gst_fdkaacenc_set_format (enc, info);
717 }
718
719 static void
720 gst_fdkaacenc_init (GstFdkAacEnc * self)
721 {
722   self->bitrate = DEFAULT_BITRATE;
723   self->enc = NULL;
724   self->is_drained = TRUE;
725   self->afterburner = FALSE;
726   self->peak_bitrate = DEFAULT_PEAK_BITRATE;
727   self->rate_control = DEFAULT_RATE_CONTROL;
728   self->vbr_preset = DEFAULT_VBR_PRESET;
729
730   gst_audio_encoder_set_drainable (GST_AUDIO_ENCODER (self), TRUE);
731 }
732
733 static void
734 gst_fdkaacenc_class_init (GstFdkAacEncClass * klass)
735 {
736   GObjectClass *object_class = G_OBJECT_CLASS (klass);
737   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
738   GstAudioEncoderClass *base_class = GST_AUDIO_ENCODER_CLASS (klass);
739
740   object_class->set_property = GST_DEBUG_FUNCPTR (gst_fdkaacenc_set_property);
741   object_class->get_property = GST_DEBUG_FUNCPTR (gst_fdkaacenc_get_property);
742
743   base_class->start = GST_DEBUG_FUNCPTR (gst_fdkaacenc_start);
744   base_class->stop = GST_DEBUG_FUNCPTR (gst_fdkaacenc_stop);
745   base_class->set_format = GST_DEBUG_FUNCPTR (gst_fdkaacenc_set_format);
746   base_class->getcaps = GST_DEBUG_FUNCPTR (gst_fdkaacenc_get_caps);
747   base_class->handle_frame = GST_DEBUG_FUNCPTR (gst_fdkaacenc_handle_frame);
748   base_class->flush = GST_DEBUG_FUNCPTR (gst_fdkaacenc_flush);
749
750   g_object_class_install_property (object_class, PROP_BITRATE,
751       g_param_spec_int ("bitrate",
752           "Bitrate",
753           "Target Audio Bitrate. Only applicable if rate-control=cbr. "
754           "(0 = fixed value based on sample rate and channel count)",
755           0, G_MAXINT, DEFAULT_BITRATE,
756           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
757
758   /**
759    * GstFdkAacEnc:peak-bitrate:
760    *
761    * Peak Bitrate to adjust maximum bits per audio frame.
762    *
763    * Since: 1.22
764    */
765   g_object_class_install_property (object_class, PROP_PEAK_BITRATE,
766       g_param_spec_int ("peak-bitrate",
767           "Peak Bitrate",
768           "Peak Bitrate to adjust maximum bits per audio frame. "
769           "Bitrate is in bits/second. Only applicable if rate-control=vbr. (0 = Not set)",
770           0, G_MAXINT, DEFAULT_PEAK_BITRATE,
771           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
772
773   /**
774    * GstFdkAacEnc:afterburner:
775    *
776    * Afterburner - Quality Parameter.
777    *
778    * Since: 1.22
779    */
780   g_object_class_install_property (object_class, PROP_AFTERBURNER,
781       g_param_spec_boolean ("afterburner", "Afterburner - Quality Parameter",
782           "Additional quality control parameter. Can cause workload increase.",
783           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
784
785   /**
786    * GstFdkAacEnc:rate-control:
787    *
788    * Rate Control.
789    *
790    * Since: 1.22
791    */
792   g_object_class_install_property (object_class, PROP_RATE_CONTROL,
793       g_param_spec_enum ("rate-control", "Rate Control",
794           "Whether Constant or Variable Bitrate should be used.",
795           GST_FDK_AAC_RATE_CONTROL, DEFAULT_RATE_CONTROL,
796           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
797
798   /**
799    * GstFdkAacEnc:vbr-preset:
800    *
801    * AAC Variable Bitrate configurations.
802    *
803    * Since: 1.22
804    */
805   g_object_class_install_property (object_class, PROP_VBR_PRESET,
806       g_param_spec_enum ("vbr-preset", "Variable Bitrate Preset",
807           "AAC Variable Bitrate configurations. Requires rate-control as vbr.",
808           GST_FDK_AAC_VBR_PRESET, DEFAULT_VBR_PRESET,
809           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
810
811   gst_element_class_add_static_pad_template (element_class, &sink_template);
812   gst_element_class_add_static_pad_template (element_class, &src_template);
813
814   gst_element_class_set_static_metadata (element_class, "FDK AAC audio encoder",
815       "Codec/Encoder/Audio/Converter", "FDK AAC audio encoder",
816       "Sebastian Dröge <sebastian@centricular.com>");
817
818   GST_DEBUG_CATEGORY_INIT (gst_fdkaacenc_debug, "fdkaacenc", 0,
819       "fdkaac encoder");
820
821   gst_type_mark_as_plugin_api (GST_FDK_AAC_VBR_PRESET, 0);
822   gst_type_mark_as_plugin_api (GST_FDK_AAC_RATE_CONTROL, 0);
823 }