diff options
author | Wim Taymans <wim.taymans@collabora.co.uk> | 2011-08-29 11:37:36 +0200 |
---|---|---|
committer | Wim Taymans <wim.taymans@collabora.co.uk> | 2011-08-29 11:37:36 +0200 |
commit | e1287b97abb8f9edfcf43db72d9dc440cafa16e3 (patch) | |
tree | 9b66c948ae22499e0d627b2c025f43ba5756a3be | |
parent | 82d82203f68eb1afbf65ac7d91721c8f65ebc005 (diff) | |
parent | 67a12c9c7298717901efce0bcfa6abbe84f97cb0 (diff) |
Merge branch 'master' into 0.11
Conflicts:
ext/ogg/gstoggmux.c
gst-libs/gst/audio/audio.c
gst-libs/gst/audio/audio.h
gst-libs/gst/audio/multichannel.h
gst-libs/gst/pbutils/Makefile.am
gst-libs/gst/pbutils/gstdiscoverer.c
gst/playback/gstplaysinkaudioconvert.c
gst/playback/gstplaysinkvideoconvert.c
win32/common/libgstaudio.def
27 files changed, 5720 insertions, 52 deletions
diff --git a/docs/libs/gst-plugins-base-libs-sections.txt b/docs/libs/gst-plugins-base-libs-sections.txt index bb794f193..bb926f497 100644 --- a/docs/libs/gst-plugins-base-libs-sections.txt +++ b/docs/libs/gst-plugins-base-libs-sections.txt @@ -2254,13 +2254,16 @@ gst_discoverer_stream_info_get_stream_type_nick gst_discoverer_info_get_audio_streams gst_discoverer_info_get_container_streams gst_discoverer_info_get_streams +gst_discoverer_info_get_subtitle_streams gst_discoverer_info_get_video_streams gst_discoverer_audio_info_get_bitrate gst_discoverer_audio_info_get_channels gst_discoverer_audio_info_get_depth +gst_discoverer_audio_info_get_language gst_discoverer_audio_info_get_max_bitrate gst_discoverer_audio_info_get_sample_rate gst_discoverer_container_info_get_streams +gst_discoverer_subtitle_info_get_language gst_discoverer_video_info_get_bitrate gst_discoverer_video_info_get_depth gst_discoverer_video_info_get_framerate_denom @@ -2308,6 +2311,7 @@ gst_discoverer_info_get_type gst_discoverer_info_copy gst_discoverer_result_get_type gst_discoverer_stream_info_get_type +gst_discoverer_subtitle_info_get_type gst_discoverer_video_info_get_type </SECTION> diff --git a/ext/ogg/gstoggdemux.c b/ext/ogg/gstoggdemux.c index f33cf328b..9847b55dc 100644 --- a/ext/ogg/gstoggdemux.c +++ b/ext/ogg/gstoggdemux.c @@ -60,7 +60,7 @@ GST_DEBUG_CATEGORY (gst_ogg_demux_setup_debug); static ogg_packet * _ogg_packet_copy (const ogg_packet * packet) { - ogg_packet *ret = g_new0 (ogg_packet, 1); + ogg_packet *ret = g_slice_new (ogg_packet); *ret = *packet; ret->packet = g_memdup (packet->packet, packet->bytes); @@ -72,13 +72,13 @@ static void _ogg_packet_free (ogg_packet * packet) { g_free (packet->packet); - g_free (packet); + g_slice_free (ogg_packet, packet); } static ogg_page * gst_ogg_page_copy (ogg_page * page) { - ogg_page *p = g_new0 (ogg_page, 1); + ogg_page *p = g_slice_new (ogg_page); /* make a copy of the page */ p->header = g_memdup (page->header, page->header_len); @@ -94,7 +94,7 @@ gst_ogg_page_free (ogg_page * page) { g_free (page->header); g_free (page->body); - g_free (page); + g_slice_free (ogg_page, page); } static gboolean gst_ogg_demux_collect_chain_info (GstOggDemux * ogg, @@ -1097,7 +1097,7 @@ choked: static GstOggChain * gst_ogg_chain_new (GstOggDemux * ogg) { - GstOggChain *chain = g_new0 (GstOggChain, 1); + GstOggChain *chain = g_slice_new0 (GstOggChain); GST_DEBUG_OBJECT (ogg, "creating new chain %p", chain); chain->ogg = ogg; @@ -1124,7 +1124,7 @@ gst_ogg_chain_free (GstOggChain * chain) gst_object_unref (pad); } g_array_free (chain->streams, TRUE); - g_free (chain); + g_slice_free (GstOggChain, chain); } static void diff --git a/ext/ogg/gstoggmux.c b/ext/ogg/gstoggmux.c index 40ce9fc2e..a0ac3cbf3 100644 --- a/ext/ogg/gstoggmux.c +++ b/ext/ogg/gstoggmux.c @@ -313,6 +313,18 @@ gst_ogg_mux_sink_event (GstPad * pad, GstEvent * event) gst_segment_init (&ogg_pad->segment, GST_FORMAT_TIME); break; } + case GST_EVENT_TAG:{ + GstTagList *tags; + + gst_event_parse_tag (event, &tags); + tags = gst_tag_list_merge (ogg_pad->tags, tags, GST_TAG_MERGE_APPEND); + if (ogg_pad->tags) + gst_tag_list_free (ogg_pad->tags); + ogg_pad->tags = tags; + + GST_DEBUG_OBJECT (ogg_mux, "Got tags %" GST_PTR_FORMAT, ogg_pad->tags); + break; + } default: break; } @@ -1144,6 +1156,66 @@ gst_ogg_mux_byte_writer_put_string_utf8 (GstByteWriter * bw, const char *s) } static void +gst_ogg_mux_add_fisbone_message_header (GstOggMux * mux, GstByteWriter * bw, + const char *tag, const char *value) +{ + /* It is valid to pass NULL as the value to omit the tag */ + if (!value) + return; + GST_DEBUG_OBJECT (mux, "Adding fisbone message header %s: %s", tag, value); + gst_ogg_mux_byte_writer_put_string_utf8 (bw, tag); + gst_ogg_mux_byte_writer_put_string_utf8 (bw, ": "); + gst_ogg_mux_byte_writer_put_string_utf8 (bw, value); + gst_ogg_mux_byte_writer_put_string_utf8 (bw, "\r\n"); +} + +static void +gst_ogg_mux_add_fisbone_message_header_from_tags (GstOggMux * mux, + GstByteWriter * bw, const char *header, const char *tag, + const GstTagList * tags) +{ + GString *s; + guint size = gst_tag_list_get_tag_size (tags, tag), n; + GST_DEBUG_OBJECT (mux, "Found %u tags for name %s", size, tag); + if (size == 0) + return; + s = g_string_new (""); + for (n = 0; n < size; ++n) { + gchar *tmp; + if (n) + g_string_append (s, ", "); + gst_tag_list_get_string_index (tags, tag, n, &tmp); + g_string_append (s, tmp); + g_free (tmp); + } + gst_ogg_mux_add_fisbone_message_header (mux, bw, header, s->str); + g_string_free (s, TRUE); +} + +/* This is a basic placeholder to generate roles for the tracks. + For tracks with more than one video, both video tracks will get + tagged with a "video/main" role, but we have no way of knowing + which one is the main one, if any. We could just pick one. For + audio, it's more complicated as we don't know which is music, + which is dubbing, etc. For kate, we could take a pretty good + guess based on the category, as role essentially is category. + For now, leave this as is. */ +static const char * +gst_ogg_mux_get_default_role (GstOggPadData * pad) +{ + const char *type = gst_ogg_stream_get_media_type (&pad->map); + if (type) { + if (!strncmp (type, "video/", strlen ("video/"))) + return "video/main"; + if (!strncmp (type, "audio/", strlen ("audio/"))) + return "audio/main"; + if (!strcmp (type + strlen (type) - strlen ("kate"), "kate")) + return "text/caption"; + } + return NULL; +} + +static void gst_ogg_mux_make_fisbone (GstOggMux * mux, ogg_stream_state * os, GstOggPadData * pad) { @@ -1165,10 +1237,14 @@ gst_ogg_mux_make_fisbone (GstOggMux * mux, ogg_stream_state * os, gst_byte_writer_put_uint8 (&bw, pad->map.granuleshift); gst_byte_writer_fill (&bw, 0, 3); /* padding */ /* message header fields - MIME type for now */ - gst_ogg_mux_byte_writer_put_string_utf8 (&bw, "Content-Type: "); - gst_ogg_mux_byte_writer_put_string_utf8 (&bw, + gst_ogg_mux_add_fisbone_message_header (mux, &bw, "Content-Type", gst_ogg_stream_get_media_type (&pad->map)); - gst_ogg_mux_byte_writer_put_string_utf8 (&bw, "\r\n"); + gst_ogg_mux_add_fisbone_message_header (mux, &bw, "Role", + gst_ogg_mux_get_default_role (pad)); + gst_ogg_mux_add_fisbone_message_header_from_tags (mux, &bw, "Language", + GST_TAG_LANGUAGE_CODE, pad->tags); + gst_ogg_mux_add_fisbone_message_header_from_tags (mux, &bw, "Title", + GST_TAG_TITLE, pad->tags); gst_ogg_mux_submit_skeleton_header_packet (mux, os, gst_byte_writer_reset_and_get_buffer (&bw), 0, 0); @@ -1920,6 +1996,11 @@ gst_ogg_mux_clear_collectpads (GstCollectPads * collect) oggpad->buffer = NULL; } + if (oggpad->tags) { + gst_tag_list_free (oggpad->tags); + oggpad->tags = NULL; + } + gst_segment_init (&oggpad->segment, GST_FORMAT_TIME); } } diff --git a/ext/ogg/gstoggmux.h b/ext/ogg/gstoggmux.h index 3db42e7a5..1e2e8a9b7 100644 --- a/ext/ogg/gstoggmux.h +++ b/ext/ogg/gstoggmux.h @@ -83,6 +83,8 @@ typedef struct gint64 keyframe_granule; /* granule of last preceding keyframe */ GstPadEventFunction collect_event; + + GstTagList *tags; } GstOggPadData; diff --git a/ext/ogg/gstoggparse.c b/ext/ogg/gstoggparse.c index 900829162..1c12bdf9e 100644 --- a/ext/ogg/gstoggparse.c +++ b/ext/ogg/gstoggparse.c @@ -117,7 +117,7 @@ free_stream (GstOggStream * stream) g_list_foreach (stream->unknown_pages, (GFunc) gst_mini_object_unref, NULL); g_list_foreach (stream->stored_buffers, (GFunc) gst_mini_object_unref, NULL); - g_free (stream); + g_slice_free (GstOggStream, stream); } static void @@ -140,7 +140,7 @@ gst_ogg_parse_new_stream (GstOggParse * parser, ogg_page * page) GST_DEBUG_OBJECT (parser, "creating new stream %08x", serialno); - stream = g_new0 (GstOggStream, 1); + stream = g_slice_new0 (GstOggStream); stream->serialno = serialno; stream->in_headers = 1; diff --git a/ext/theora/gsttheoraenc.c b/ext/theora/gsttheoraenc.c index 29aa3f3f1..9dc8387f3 100644 --- a/ext/theora/gsttheoraenc.c +++ b/ext/theora/gsttheoraenc.c @@ -607,7 +607,7 @@ theora_enc_sink_getcaps (GstPad * pad, GstCaps * filter) peer = gst_pad_get_peer (encoder->srcpad); if (peer) { const GstCaps *templ_caps; - GstCaps *peer_caps; + GstCaps *peer_caps, *tmp_caps; GstStructure *s; guint i, n; @@ -625,8 +625,9 @@ theora_enc_sink_getcaps (GstPad * pad, GstCaps * filter) templ_caps = gst_pad_get_pad_template_caps (pad); - caps = gst_caps_intersect (peer_caps, templ_caps); - caps = gst_caps_intersect (caps, theora_enc_src_caps); + tmp_caps = gst_caps_intersect (peer_caps, templ_caps); + caps = gst_caps_intersect (tmp_caps, theora_enc_src_caps); + gst_caps_unref (tmp_caps); gst_caps_unref (peer_caps); gst_object_unref (peer); peer = NULL; diff --git a/gst-libs/gst/Makefile.am b/gst-libs/gst/Makefile.am index c776f8eb7..6f261b3d6 100644 --- a/gst-libs/gst/Makefile.am +++ b/gst-libs/gst/Makefile.am @@ -5,23 +5,23 @@ SUBDIRS = \ interfaces \ tag \ - audio \ cdda \ fft \ floatcast \ netbuffer \ - riff \ rtp \ sdp \ rtsp \ video \ pbutils \ + audio \ + riff \ app noinst_HEADERS = gettext.h gst-i18n-plugin.h # dependencies: -audio: interfaces +audio: interfaces pbutils cdda: tag @@ -29,10 +29,8 @@ riff: tag audio rtsp: sdp -pbutils: video - INDEPENDENT_SUBDIRS = \ - interfaces tag fft floatcast netbuffer rtp sdp video app + interfaces tag fft floatcast netbuffer pbutils rtp sdp video app .PHONY: independent-subdirs $(INDEPENDENT_SUBDIRS) diff --git a/gst-libs/gst/audio/Makefile.am b/gst-libs/gst/audio/Makefile.am index bf38ead07..4e5413e6b 100644 --- a/gst-libs/gst/audio/Makefile.am +++ b/gst-libs/gst/audio/Makefile.am @@ -22,6 +22,8 @@ libgstaudio_@GST_MAJORMINOR@_la_SOURCES = \ gstaudioclock.c \ mixerutils.c \ multichannel.c \ + gstbaseaudiodecoder.c \ + gstbaseaudioencoder.c \ gstbaseaudiosink.c \ gstbaseaudiosrc.c \ gstaudiofilter.c \ @@ -36,6 +38,8 @@ libgstaudio_@GST_MAJORMINOR@include_HEADERS = \ gstringbuffer.h \ gstaudioclock.h \ gstaudiofilter.h \ + gstbaseaudiodecoder.h \ + gstbaseaudioencoder.h \ gstbaseaudiosink.h \ gstbaseaudiosrc.h \ gstaudiosink.h \ @@ -49,6 +53,7 @@ nodist_libgstaudio_@GST_MAJORMINOR@include_HEADERS = \ libgstaudio_@GST_MAJORMINOR@_la_CFLAGS = $(GST_PLUGINS_BASE_CFLAGS) $(GST_BASE_CFLAGS) $(GST_CFLAGS) libgstaudio_@GST_MAJORMINOR@_la_LIBADD = $(GST_BASE_LIBS) $(GST_LIBS) \ + $(top_builddir)/gst-libs/gst/pbutils/libgstpbutils-@GST_MAJORMINOR@.la \ $(top_builddir)/gst-libs/gst/interfaces/libgstinterfaces-@GST_MAJORMINOR@.la libgstaudio_@GST_MAJORMINOR@_la_LDFLAGS = $(GST_LIB_LDFLAGS) $(GST_ALL_LDFLAGS) $(GST_LT_LDFLAGS) diff --git a/gst-libs/gst/audio/audio.c b/gst-libs/gst/audio/audio.c index 2416c58e6..fda6e0742 100644 --- a/gst-libs/gst/audio/audio.c +++ b/gst-libs/gst/audio/audio.c @@ -504,6 +504,437 @@ done: } +#define SINT (GST_AUDIO_FORMAT_FLAG_INTEGER | GST_AUDIO_FORMAT_FLAG_SIGNED) +#define UINT (GST_AUDIO_FORMAT_FLAG_INTEGER) + +#define MAKE_FORMAT(str,flags,end,width,depth,silent) \ + { GST_AUDIO_FORMAT_ ##str, G_STRINGIFY(str), flags, end, width, depth, silent } + +#define SILENT_0 { 0, 0, 0, 0, 0, 0, 0, 0 } +#define SILENT_U8 { 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 } +#define SILENT_U16_LE { 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80 } +#define SILENT_U16_BE { 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00 } +#define SILENT_U24_LE { 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00 } +#define SILENT_U24_BE { 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00 } +#define SILENT_U32_LE { 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80 } +#define SILENT_U32_BE { 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00 } +#define SILENT_U24_3LE { 0x00, 0x00, 0x80, 0x00, 0x00, 0x80 } +#define SILENT_U24_3BE { 0x80, 0x00, 0x00, 0x80, 0x00, 0x00 } +#define SILENT_U20_3LE { 0x00, 0x00, 0x08, 0x00, 0x00, 0x08 } +#define SILENT_U20_3BE { 0x08, 0x00, 0x00, 0x08, 0x00, 0x00 } +#define SILENT_U18_3LE { 0x00, 0x00, 0x02, 0x00, 0x00, 0x02 } +#define SILENT_U18_3BE { 0x02, 0x00, 0x00, 0x02, 0x00, 0x00 } + +static GstAudioFormatInfo formats[] = { + {GST_AUDIO_FORMAT_UNKNOWN, "UNKNOWN", 0, 0, 0, 0}, + /* 8 bit */ + MAKE_FORMAT (S8, SINT, 0, 8, 8, SILENT_0), + MAKE_FORMAT (U8, UINT, 0, 8, 8, SILENT_U8), + /* 16 bit */ + MAKE_FORMAT (S16_LE, SINT, G_LITTLE_ENDIAN, 16, 16, SILENT_0), + MAKE_FORMAT (S16_BE, SINT, G_BIG_ENDIAN, 16, 16, SILENT_0), + MAKE_FORMAT (U16_LE, UINT, G_LITTLE_ENDIAN, 16, 16, SILENT_U16_LE), + MAKE_FORMAT (U16_BE, UINT, G_BIG_ENDIAN, 16, 16, SILENT_U16_BE), + /* 24 bit in low 3 bytes of 32 bits */ + MAKE_FORMAT (S24_LE, SINT, G_LITTLE_ENDIAN, 32, 24, SILENT_0), + MAKE_FORMAT (S24_BE, SINT, G_BIG_ENDIAN, 32, 24, SILENT_0), + MAKE_FORMAT (U24_LE, UINT, G_LITTLE_ENDIAN, 32, 24, SILENT_U24_LE), + MAKE_FORMAT (U24_BE, UINT, G_BIG_ENDIAN, 32, 24, SILENT_U24_BE), + /* 32 bit */ + MAKE_FORMAT (S32_LE, SINT, G_LITTLE_ENDIAN, 32, 32, SILENT_0), + MAKE_FORMAT (S32_BE, SINT, G_BIG_ENDIAN, 32, 32, SILENT_0), + MAKE_FORMAT (U32_LE, UINT, G_LITTLE_ENDIAN, 32, 32, SILENT_U32_LE), + MAKE_FORMAT (U32_BE, UINT, G_BIG_ENDIAN, 32, 32, SILENT_U32_BE), + /* 24 bit in 3 bytes */ + MAKE_FORMAT (S24_3LE, SINT, G_LITTLE_ENDIAN, 24, 24, SILENT_0), + MAKE_FORMAT (S24_3BE, SINT, G_BIG_ENDIAN, 24, 24, SILENT_0), + MAKE_FORMAT (U24_3LE, UINT, G_LITTLE_ENDIAN, 24, 24, SILENT_U24_3LE), + MAKE_FORMAT (U24_3BE, UINT, G_BIG_ENDIAN, 24, 24, SILENT_U24_3BE), + /* 20 bit in 3 bytes */ + MAKE_FORMAT (S20_3LE, SINT, G_LITTLE_ENDIAN, 24, 20, SILENT_0), + MAKE_FORMAT (S20_3BE, SINT, G_BIG_ENDIAN, 24, 20, SILENT_0), + MAKE_FORMAT (U20_3LE, UINT, G_LITTLE_ENDIAN, 24, 20, SILENT_U20_3LE), + MAKE_FORMAT (U20_3BE, UINT, G_BIG_ENDIAN, 24, 20, SILENT_U20_3BE), + /* 18 bit in 3 bytes */ + MAKE_FORMAT (S18_3LE, SINT, G_LITTLE_ENDIAN, 24, 18, SILENT_0), + MAKE_FORMAT (S18_3BE, SINT, G_BIG_ENDIAN, 24, 18, SILENT_0), + MAKE_FORMAT (U18_3LE, UINT, G_LITTLE_ENDIAN, 24, 18, SILENT_U18_3LE), + MAKE_FORMAT (U18_3BE, UINT, G_BIG_ENDIAN, 24, 18, SILENT_U18_3BE), + /* float */ + MAKE_FORMAT (F32_LE, GST_AUDIO_FORMAT_FLAG_FLOAT, G_LITTLE_ENDIAN, 32, 32, + SILENT_0), + MAKE_FORMAT (F32_BE, GST_AUDIO_FORMAT_FLAG_FLOAT, G_BIG_ENDIAN, 32, 32, + SILENT_0), + MAKE_FORMAT (F64_LE, GST_AUDIO_FORMAT_FLAG_FLOAT, G_LITTLE_ENDIAN, 64, 64, + SILENT_0), + MAKE_FORMAT (F64_BE, GST_AUDIO_FORMAT_FLAG_FLOAT, G_BIG_ENDIAN, 64, 64, + SILENT_0) +}; + +static GstAudioFormat +gst_audio_format_from_caps_structure (const GstStructure * s) +{ + gint endianness, width, depth; + guint i; + + if (gst_structure_has_name (s, "audio/x-raw-int")) { + gboolean sign; + + if (!gst_structure_get_boolean (s, "signed", &sign)) + goto missing_field_signed; + + if (!gst_structure_get_int (s, "endianness", &endianness)) + goto missing_field_endianness; + + if (!gst_structure_get_int (s, "width", &width)) + goto missing_field_width; + + if (!gst_structure_get_int (s, "depth", &depth)) + goto missing_field_depth; + + for (i = 0; i < G_N_ELEMENTS (formats); i++) { + if (GST_AUDIO_FORMAT_INFO_IS_INTEGER (&formats[i]) && + sign == GST_AUDIO_FORMAT_INFO_IS_SIGNED (&formats[i]) && + GST_AUDIO_FORMAT_INFO_ENDIANNESS (&formats[i]) == endianness && + GST_AUDIO_FORMAT_INFO_WIDTH (&formats[i]) == width && + GST_AUDIO_FORMAT_INFO_DEPTH (&formats[i]) == depth) { + return GST_AUDIO_FORMAT_INFO_FORMAT (&formats[i]); + } + } + } else if (gst_structure_has_name (s, "audio/x-raw-float")) { + /* fallbacks are for backwards compatibility (is this needed at all?) */ + if (!gst_structure_get_int (s, "endianness", &endianness)) { + GST_WARNING ("float audio caps without endianness %" GST_PTR_FORMAT, s); + endianness = G_BYTE_ORDER; + } + + if (!gst_structure_get_int (s, "width", &width)) { + GST_WARNING ("float audio caps without width %" GST_PTR_FORMAT, s); + width = 32; + } + + for (i = 0; i < G_N_ELEMENTS (formats); i++) { + if (GST_AUDIO_FORMAT_INFO_IS_FLOAT (&formats[i]) && + GST_AUDIO_FORMAT_INFO_ENDIANNESS (&formats[i]) == endianness && + GST_AUDIO_FORMAT_INFO_WIDTH (&formats[i]) == width) { + return GST_AUDIO_FORMAT_INFO_FORMAT (&formats[i]); + } + } + } + + /* no match */ + return GST_AUDIO_FORMAT_UNKNOWN; + +missing_field_signed: + { + GST_ERROR ("missing 'signed' field in audio caps %" GST_PTR_FORMAT, s); + return GST_AUDIO_FORMAT_UNKNOWN; + } +missing_field_endianness: + { + GST_ERROR ("missing 'endianness' field in audio caps %" GST_PTR_FORMAT, s); + return GST_AUDIO_FORMAT_UNKNOWN; + } +missing_field_depth: + { + GST_ERROR ("missing 'depth' field in audio caps %" GST_PTR_FORMAT, s); + return GST_AUDIO_FORMAT_UNKNOWN; + } +missing_field_width: + { + GST_ERROR ("missing 'width' field in audio caps %" GST_PTR_FORMAT, s); + return GST_AUDIO_FORMAT_UNKNOWN; + } +} + +/* FIXME: remove these if we don't actually go for deep alloc positions */ +void +gst_audio_info_init (GstAudioInfo * info) +{ + memset (info, 0, sizeof (GstAudioInfo)); +} + +void +gst_audio_info_clear (GstAudioInfo * info) +{ + memset (info, 0, sizeof (GstAudioInfo)); +} + +GstAudioInfo * +gst_audio_info_copy (GstAudioInfo * info) +{ + return (GstAudioInfo *) g_slice_copy (sizeof (GstAudioInfo), info); +} + +void +gst_audio_info_free (GstAudioInfo * info) +{ + g_slice_free (GstAudioInfo, info); +} + +static void +gst_audio_info_set_format (GstAudioInfo * info, GstAudioFormat format, + gint rate, gint channels) +{ + const GstAudioFormatInfo *finfo; + + g_return_if_fail (info != NULL); + g_return_if_fail (format != GST_AUDIO_FORMAT_UNKNOWN); + + finfo = &formats[format]; + + info->flags = 0; + info->finfo = finfo; + info->rate = rate; + info->channels = channels; + info->bpf = (finfo->width * channels) / 8; +} + +/* from multichannel.c */ +void priv_gst_audio_info_fill_default_channel_positions (GstAudioInfo * info); + +/** + * gst_audio_info_from_caps: + * @info: a #GstAudioInfo + * @caps: a #GstCaps + * + * Parse @caps and update @info. + * + * Returns: TRUE if @caps could be parsed + * + * Since: 0.10.36 + */ +gboolean +gst_audio_info_from_caps (GstAudioInfo * info, const GstCaps * caps) +{ + GstStructure *str; + GstAudioFormat format; + gint rate, channels; + const GValue *pos_val_arr, *pos_val_entry; + gint i; + + g_return_val_if_fail (info != NULL, FALSE); + g_return_val_if_fail (caps != NULL, FALSE); + g_return_val_if_fail (gst_caps_is_fixed (caps), FALSE); + + GST_DEBUG ("parsing caps %" GST_PTR_FORMAT, caps); + + str = gst_caps_get_structure (caps, 0); + + format = gst_audio_format_from_caps_structure (str); + if (format == GST_AUDIO_FORMAT_UNKNOWN) + goto unknown_format; + + if (!gst_structure_get_int (str, "rate", &rate)) + goto no_rate; + if (!gst_structure_get_int (str, "channels", &channels)) + goto no_channels; + + gst_audio_info_set_format (info, format, rate, channels); + + pos_val_arr = gst_structure_get_value (str, "channel-positions"); + if (pos_val_arr) { + if (channels <= G_N_ELEMENTS (info->position)) { + for (i = 0; i < channels; i++) { + pos_val_entry = gst_value_array_get_value (pos_val_arr, i); + info->position[i] = g_value_get_enum (pos_val_entry); + } + } else { + /* for that many channels, the positions are always NONE */ + for (i = 0; i < G_N_ELEMENTS (info->position); i++) + info->position[i] = GST_AUDIO_CHANNEL_POSITION_NONE; + info->flags |= GST_AUDIO_FLAG_DEFAULT_POSITIONS; + } + } else { + info->flags |= GST_AUDIO_FLAG_DEFAULT_POSITIONS; + priv_gst_audio_info_fill_default_channel_positions (info); + } + + return TRUE; + + /* ERROR */ +unknown_format: + { + GST_ERROR ("unknown format given"); + return FALSE; + } +no_rate: + { + GST_ERROR ("no rate property given"); + return FALSE; + } +no_channels: + { + GST_ERROR ("no channels property given"); + return FALSE; + } +} + +/** + * gst_audio_info_to_caps: + * @info: a #GstAudioInfo + * + * Convert the values of @info into a #GstCaps. + * + * Returns: (transfer full): the new #GstCaps containing the + * info of @info. + * + * Since: 0.10.36 + */ +GstCaps * +gst_audio_info_to_caps (GstAudioInfo * info) +{ + GstCaps *caps; + + g_return_val_if_fail (info != NULL, NULL); + g_return_val_if_fail (info->finfo != NULL, NULL); + g_return_val_if_fail (info->finfo->format != GST_AUDIO_FORMAT_UNKNOWN, NULL); + + if (GST_AUDIO_FORMAT_INFO_IS_INTEGER (info->finfo)) { + caps = gst_caps_new_simple ("audio/x-raw-int", + "width", G_TYPE_INT, GST_AUDIO_INFO_WIDTH (info), + "depth", G_TYPE_INT, GST_AUDIO_INFO_DEPTH (info), + "endianness", G_TYPE_INT, + GST_AUDIO_FORMAT_INFO_ENDIANNESS (info->finfo), "signed", + G_TYPE_BOOLEAN, GST_AUDIO_FORMAT_INFO_IS_SIGNED (info->finfo), "rate", + G_TYPE_INT, GST_AUDIO_INFO_RATE (info), "channels", G_TYPE_INT, + GST_AUDIO_INFO_CHANNELS (info), NULL); + } else if (GST_AUDIO_FORMAT_INFO_IS_FLOAT (info->finfo)) { + caps = gst_caps_new_simple ("audio/x-raw-float", + "width", G_TYPE_INT, GST_AUDIO_INFO_WIDTH (info), + "endianness", G_TYPE_INT, + GST_AUDIO_FORMAT_INFO_ENDIANNESS (info->finfo), "rate", G_TYPE_INT, + GST_AUDIO_INFO_RATE (info), "channels", G_TYPE_INT, + GST_AUDIO_INFO_CHANNELS (info), NULL); + } else { + GST_ERROR ("unknown audio format, neither integer nor float"); + return NULL; + } + + if (info->channels > 2) { + GValue pos_val_arr = { 0 } + , pos_val_entry = { + 0}; + GstStructure *str; + gint i; + + /* build gvaluearray from positions */ + g_value_init (&pos_val_arr, GST_TYPE_ARRAY); + g_value_init (&pos_val_entry, GST_TYPE_AUDIO_CHANNEL_POSITION); + for (i = 0; i < info->channels; i++) { + /* if we have many many channels, all positions are NONE */ + if (info->channels <= 64) + g_value_set_enum (&pos_val_entry, info->position[i]); + else + g_value_set_enum (&pos_val_entry, GST_AUDIO_CHANNEL_POSITION_NONE); + + gst_value_array_append_value (&pos_val_arr, &pos_val_entry); + } + g_value_unset (&pos_val_entry); + + /* add to structure */ + str = gst_caps_get_structure (caps, 0); + gst_structure_set_value (str, "channel-positions", &pos_val_arr); + g_value_unset (&pos_val_arr); + } + + return caps; +} + +/** + * gst_audio_format_convert: + * @info: a #GstAudioInfo + * @src_format: #GstFormat of the @src_value + * @src_value: value to convert + * @dest_format: #GstFormat of the @dest_value + * @dest_value: pointer to destination value + * + * Converts among various #GstFormat types. This function handles + * GST_FORMAT_BYTES, GST_FORMAT_TIME, and GST_FORMAT_DEFAULT. For + * raw audio, GST_FORMAT_DEFAULT corresponds to audio frames. This + * function can be used to handle pad queries of the type GST_QUERY_CONVERT. + * + * Returns: TRUE if the conversion was successful. + * + * Since: 0.10.36 + */ +gboolean +gst_audio_info_convert (GstAudioInfo * info, + GstFormat src_fmt, gint64 src_val, GstFormat dest_fmt, gint64 * dest_val) +{ + gboolean res = TRUE; + gint bpf, rate; + + GST_DEBUG ("converting value %" G_GINT64_FORMAT " from %s (%d) to %s (%d)", + src_val, gst_format_get_name (src_fmt), src_fmt, + gst_format_get_name (dest_fmt), dest_fmt); + + if (src_fmt == dest_fmt || src_val == -1) { + *dest_val = src_val; + goto done; + } + + /* get important info */ + bpf = GST_AUDIO_INFO_BPF (info); + rate = GST_AUDIO_INFO_RATE (info); + + if (bpf == 0 || rate == 0) { + GST_DEBUG ("no rate or bpf configured"); + res = FALSE; + goto done; + } + + switch (src_fmt) { + case GST_FORMAT_BYTES: + switch (dest_fmt) { + case GST_FORMAT_TIME: + *dest_val = GST_FRAMES_TO_CLOCK_TIME (src_val / bpf, rate); + break; + case GST_FORMAT_DEFAULT: + *dest_val = src_val / bpf; + break; + default: + res = FALSE; + break; + } + break; + case GST_FORMAT_DEFAULT: + switch (dest_fmt) { + case GST_FORMAT_TIME: + *dest_val = GST_FRAMES_TO_CLOCK_TIME (src_val, rate); + break; + case GST_FORMAT_BYTES: + *dest_val = src_val * bpf; + break; + default: + res = FALSE; + break; + } + break; + case GST_FORMAT_TIME: + switch (dest_fmt) { + case GST_FORMAT_DEFAULT: + *dest_val = GST_CLOCK_TIME_TO_FRAMES (src_val, rate); + break; + case GST_FORMAT_BYTES: + *dest_val = GST_CLOCK_TIME_TO_FRAMES (src_val, rate); + *dest_val *= bpf; + break; + default: + res = FALSE; + break; + } + break; + default: + res = FALSE; + break; + } +done: + GST_DEBUG ("ret=%d result %" G_GINT64_FORMAT, res, *dest_val); + + return res; +} + /** * gst_audio_buffer_clip: * @buffer: The buffer to clip. diff --git a/gst-libs/gst/audio/gstbaseaudiodecoder.c b/gst-libs/gst/audio/gstbaseaudiodecoder.c new file mode 100644 index 000000000..637e140af --- /dev/null +++ b/gst-libs/gst/audio/gstbaseaudiodecoder.c @@ -0,0 +1,2320 @@ +/* GStreamer + * Copyright (C) 2009 Igalia S.L. + * Author: Iago Toral Quiroga <itoral@igalia.com> + * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>. + * Copyright (C) 2011 Nokia Corporation. All rights reserved. + * Contact: Stefan Kost <stefan.kost@nokia.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +/** + * SECTION:gstbaseaudiodecoder + * @short_description: Base class for audio decoders + * @see_also: #GstBaseTransform + * @since: 0.10.36 + * + * This base class is for audio decoders turning encoded data into + * raw audio samples. + * + * GstBaseAudioDecoder and subclass should cooperate as follows. + * <orderedlist> + * <listitem> + * <itemizedlist><title>Configuration</title> + * <listitem><para> + * Initially, GstBaseAudioDecoder calls @start when the decoder element + * is activated, which allows subclass to perform any global setup. + * Base class (context) parameters can already be set according to subclass + * capabilities (or possibly upon receive more information in subsequent + * @set_format). + * </para></listitem> + * <listitem><para> + * GstBaseAudioDecoder calls @set_format to inform subclass of the format + * of input audio data that it is about to receive. + * While unlikely, it might be called more than once, if changing input + * parameters require reconfiguration. + * </para></listitem> + * <listitem><para> + * GstBaseAudioDecoder calls @stop at end of all processing. + * </para></listitem> + * </itemizedlist> + * </listitem> + * As of configuration stage, and throughout processing, GstBaseAudioDecoder + * provides various (context) parameters, e.g. describing the format of + * output audio data (valid when output caps have been caps) or current parsing state. + * Conversely, subclass can and should configure context to inform + * base class of its expectation w.r.t. buffer handling. + * <listitem> + * <itemizedlist> + * <title>Data processing</title> + * <listitem><para> + * Base class gathers input data, and optionally allows subclass + * to parse this into subsequently manageable (as defined by subclass) + * chunks. Such chunks are subsequently referred to as 'frames', + * though they may or may not correspond to 1 (or more) audio format frame. + * </para></listitem> + * <listitem><para> + * Input frame is provided to subclass' @handle_frame. + * </para></listitem> + * <listitem><para> + * If codec processing results in decoded data, subclass should call + * @gst_base_audio_decoder_finish_frame to have decoded data pushed + * downstream. + * </para></listitem> + * <listitem><para> + * Just prior to actually pushing a buffer downstream, + * it is passed to @pre_push. Subclass should either use this callback + * to arrange for additional downstream pushing or otherwise ensure such + * custom pushing occurs after at least a method call has finished since + * setting src pad caps. + * </para></listitem> + * <listitem><para> + * During the parsing process GstBaseAudioDecoderClass will handle both + * srcpad and sinkpad events. Sink events will be passed to subclass + * if @event callback has been provided. + * </para></listitem> + * </itemizedlist> + * </listitem> + * <listitem> + * <itemizedlist><title>Shutdown phase</title> + * <listitem><para> + * GstBaseAudioDecoder class calls @stop to inform the subclass that data + * parsing will be stopped. + * </para></listitem> + * </itemizedlist> + * </listitem> + * </orderedlist> + * + * Subclass is responsible for providing pad template caps for + * source and sink pads. The pads need to be named "sink" and "src". It also + * needs to set the fixed caps on srcpad, when the format is ensured. This + * is typically when base class calls subclass' @set_format function, though + * it might be delayed until calling @gst_base_audio_decoder_finish_frame. + * + * In summary, above process should have subclass concentrating on + * codec data processing while leaving other matters to base class, + * such as most notably timestamp handling. While it may exert more control + * in this area (see e.g. @pre_push), it is very much not recommended. + * + * In particular, base class will try to arrange for perfect output timestamps + * as much as possible while tracking upstream timestamps. + * To this end, if deviation between the next ideal expected perfect timestamp + * and upstream exceeds #GstBaseAudioDecoder:tolerance, then resync to upstream + * occurs (which would happen always if the tolerance mechanism is disabled). + * + * In non-live pipelines, baseclass can also (configurably) arrange for + * output buffer aggregation which may help to redue large(r) numbers of + * small(er) buffers being pushed and processed downstream. + * + * On the other hand, it should be noted that baseclass only provides limited + * seeking support (upon explicit subclass request), as full-fledged support + * should rather be left to upstream demuxer, parser or alike. This simple + * approach caters for seeking and duration reporting using estimated input + * bitrates. + * + * Things that subclass need to take care of: + * <itemizedlist> + * <listitem><para>Provide pad templates</para></listitem> + * <listitem><para> + * Set source pad caps when appropriate + * </para></listitem> + * <listitem><para> + * Set user-configurable properties to sane defaults for format and + * implementing codec at hand, and convey some subclass capabilities and + * expectations in context. + * </para></listitem> + * <listitem><para> + * Accept data in @handle_frame and provide encoded results to + * @gst_base_audio_decoder_finish_frame. If it is prepared to perform + * PLC, it should also accept NULL data in @handle_frame and provide for + * data for indicated duration. + * </para></listitem> + * </itemizedlist> + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#define GST_USE_UNSTABLE_API +#include "gstbaseaudiodecoder.h" +#include <gst/pbutils/descriptions.h> + +#include <string.h> + +GST_DEBUG_CATEGORY (baseaudiodecoder_debug); +#define GST_CAT_DEFAULT baseaudiodecoder_debug + +#define GST_BASE_AUDIO_DECODER_GET_PRIVATE(obj) \ + (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_AUDIO_DECODER, \ + GstBaseAudioDecoderPrivate)) + +enum +{ + LAST_SIGNAL +}; + +enum +{ + PROP_0, + PROP_LATENCY, + PROP_TOLERANCE, + PROP_PLC +}; + +#define DEFAULT_LATENCY 0 +#define DEFAULT_TOLERANCE 0 +#define DEFAULT_PLC FALSE + +typedef struct _GstBaseAudioDecoderContext +{ + /* input */ + /* (output) audio format */ + GstAudioInfo info; + + /* parsing state */ + gboolean eos; + gboolean sync; + + /* misc */ + gint delay; + + /* output */ + gboolean do_plc; + gboolean do_byte_time; + gint max_errors; + /* MT-protected (with LOCK) */ + GstClockTime min_latency; + GstClockTime max_latency; +} GstBaseAudioDecoderContext; + +struct _GstBaseAudioDecoderPrivate +{ + /* activation status */ + gboolean active; + + /* input base/first ts as basis for output ts */ + GstClockTime base_ts; + /* input samples processed and sent downstream so far (w.r.t. base_ts) */ + guint64 samples; + + /* collected input data */ + GstAdapter *adapter; + /* tracking input ts for changes */ + GstClockTime prev_ts; + /* frames obtained from input */ + GQueue frames; + /* collected output data */ + GstAdapter *adapter_out; + /* ts and duration for output data collected above */ + GstClockTime out_ts, out_dur; + /* mark outgoing discont */ + gboolean discont; + + /* subclass gave all it could already */ + gboolean drained; + /* subclass currently being forcibly drained */ + gboolean force; + + /* input bps estimatation */ + /* global in bytes seen */ + guint64 bytes_in; + /* global samples sent out */ + guint64 samples_out; + /* bytes flushed during parsing */ + guint sync_flush; + /* error count */ + gint error_count; + /* codec id tag */ + GstTagList *taglist; + + /* whether circumstances allow output aggregation */ + gint agg; + + /* reverse playback queues */ + /* collect input */ + GList *gather; + /* to-be-decoded */ + GList *decode; + /* reversed output */ + GList *queued; + + /* context storage */ + GstBaseAudioDecoderContext ctx; + + /* properties */ + GstClockTime latency; + GstClockTime tolerance; + gboolean plc; + +}; + + +static void gst_base_audio_decoder_finalize (GObject * object); +static void gst_base_audio_decoder_set_property (GObject * object, + guint prop_id, const GValue * value, GParamSpec * pspec); +static void gst_base_audio_decoder_get_property (GObject * object, + guint prop_id, GValue * value, GParamSpec * pspec); + +static void gst_base_audio_decoder_clear_queues (GstBaseAudioDecoder * dec); +static GstFlowReturn gst_base_audio_decoder_chain_reverse (GstBaseAudioDecoder * + dec, GstBuffer * buf); + +static GstStateChangeReturn gst_base_audio_decoder_change_state (GstElement * + element, GstStateChange transition); +static gboolean gst_base_audio_decoder_sink_event (GstPad * pad, + GstEvent * event); +static gboolean gst_base_audio_decoder_src_event (GstPad * pad, + GstEvent * event); +static gboolean gst_base_audio_decoder_sink_setcaps (GstPad * pad, + GstCaps * caps); +static gboolean gst_base_audio_decoder_src_setcaps (GstPad * pad, + GstCaps * caps); +static GstFlowReturn gst_base_audio_decoder_chain (GstPad * pad, + GstBuffer * buf); +static gboolean gst_base_audio_decoder_src_query (GstPad * pad, + GstQuery * query); +static gboolean gst_base_audio_decoder_sink_query (GstPad * pad, + GstQuery * query); +static const GstQueryType *gst_base_audio_decoder_get_query_types (GstPad * + pad); +static void gst_base_audio_decoder_reset (GstBaseAudioDecoder * dec, + gboolean full); + + +GST_BOILERPLATE (GstBaseAudioDecoder, gst_base_audio_decoder, GstElement, + GST_TYPE_ELEMENT); + +static void +gst_base_audio_decoder_base_init (gpointer g_class) +{ +} + +static void +gst_base_audio_decoder_class_init (GstBaseAudioDecoderClass * klass) +{ + GObjectClass *gobject_class; + GstElementClass *element_class; + + gobject_class = G_OBJECT_CLASS (klass); + element_class = GST_ELEMENT_CLASS (klass); + + parent_class = g_type_class_peek_parent (klass); + + g_type_class_add_private (klass, sizeof (GstBaseAudioDecoderPrivate)); + + GST_DEBUG_CATEGORY_INIT (baseaudiodecoder_debug, "baseaudiodecoder", 0, + "baseaudiodecoder element"); + + gobject_class->set_property = gst_base_audio_decoder_set_property; + gobject_class->get_property = gst_base_audio_decoder_get_property; + gobject_class->finalize = gst_base_audio_decoder_finalize; + + element_class->change_state = gst_base_audio_decoder_change_state; + + /* Properties */ + g_object_class_install_property (gobject_class, PROP_LATENCY, + g_param_spec_int64 ("min-latency", "Minimum Latency", + "Aggregate output data to a minimum of latency time (ns)", + 0, G_MAXINT64, DEFAULT_LATENCY, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + g_object_class_install_property (gobject_class, PROP_TOLERANCE, + g_param_spec_int64 ("tolerance", "Tolerance", + "Perfect ts while timestamp jitter/imperfection within tolerance (ns)", + 0, G_MAXINT64, DEFAULT_TOLERANCE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + g_object_class_install_property (gobject_class, PROP_PLC, + g_param_spec_boolean ("plc", "Packet Loss Concealment", + "Perform packet loss concealment (if supported)", + DEFAULT_PLC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gst_base_audio_decoder_init (GstBaseAudioDecoder * dec, + GstBaseAudioDecoderClass * klass) +{ + GstPadTemplate *pad_template; + + GST_DEBUG_OBJECT (dec, "gst_base_audio_decoder_init"); + + dec->priv = GST_BASE_AUDIO_DECODER_GET_PRIVATE (dec); + + /* Setup sink pad */ + pad_template = + gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink"); + g_return_if_fail (pad_template != NULL); + + dec->sinkpad = gst_pad_new_from_template (pad_template, "sink"); + gst_pad_set_event_function (dec->sinkpad, + GST_DEBUG_FUNCPTR (gst_base_audio_decoder_sink_event)); + gst_pad_set_setcaps_function (dec->sinkpad, + GST_DEBUG_FUNCPTR (gst_base_audio_decoder_sink_setcaps)); + gst_pad_set_chain_function (dec->sinkpad, + GST_DEBUG_FUNCPTR (gst_base_audio_decoder_chain)); + gst_pad_set_query_function (dec->sinkpad, + GST_DEBUG_FUNCPTR (gst_base_audio_decoder_sink_query)); + gst_element_add_pad (GST_ELEMENT (dec), dec->sinkpad); + GST_DEBUG_OBJECT (dec, "sinkpad created"); + + /* Setup source pad */ + pad_template = + gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src"); + g_return_if_fail (pad_template != NULL); + + dec->srcpad = gst_pad_new_from_template (pad_template, "src"); + gst_pad_set_setcaps_function (dec->srcpad, + GST_DEBUG_FUNCPTR (gst_base_audio_decoder_src_setcaps)); + gst_pad_set_event_function (dec->srcpad, + GST_DEBUG_FUNCPTR (gst_base_audio_decoder_src_event)); + gst_pad_set_query_function (dec->srcpad, + GST_DEBUG_FUNCPTR (gst_base_audio_decoder_src_query)); + gst_pad_set_query_type_function (dec->srcpad, + GST_DEBUG_FUNCPTR (gst_base_audio_decoder_get_query_types)); + gst_pad_use_fixed_caps (dec->srcpad); + gst_element_add_pad (GST_ELEMENT (dec), dec->srcpad); + GST_DEBUG_OBJECT (dec, "srcpad created"); + + dec->priv->adapter = gst_adapter_new (); + dec->priv->adapter_out = gst_adapter_new (); + g_queue_init (&dec->priv->frames); + + /* property default */ + dec->priv->latency = DEFAULT_LATENCY; + dec->priv->tolerance = DEFAULT_TOLERANCE; + dec->priv->plc = DEFAULT_PLC; + + /* init state */ + gst_base_audio_decoder_reset (dec, TRUE); + GST_DEBUG_OBJECT (dec, "init ok"); +} + +static void +gst_base_audio_decoder_reset (GstBaseAudioDecoder * dec, gboolean full) +{ + GST_DEBUG_OBJECT (dec, "gst_base_audio_decoder_reset"); + + GST_OBJECT_LOCK (dec); + + if (full) { + dec->priv->active = FALSE; + dec->priv->bytes_in = 0; + dec->priv->samples_out = 0; + dec->priv->agg = -1; + dec->priv->error_count = 0; + gst_base_audio_decoder_clear_queues (dec); + + gst_audio_info_clear (&dec->priv->ctx.info); + memset (&dec->priv->ctx, 0, sizeof (dec->priv->ctx)); + + if (dec->priv->taglist) { + gst_tag_list_free (dec->priv->taglist); + dec->priv->taglist = NULL; + } + + gst_segment_init (&dec->segment, GST_FORMAT_TIME); + } + + g_queue_foreach (&dec->priv->frames, (GFunc) gst_buffer_unref, NULL); + g_queue_clear (&dec->priv->frames); + gst_adapter_clear (dec->priv->adapter); + gst_adapter_clear (dec->priv->adapter_out); + dec->priv->out_ts = GST_CLOCK_TIME_NONE; + dec->priv->out_dur = 0; + dec->priv->prev_ts = GST_CLOCK_TIME_NONE; + dec->priv->drained = TRUE; + dec->priv->base_ts = GST_CLOCK_TIME_NONE; + dec->priv->samples = 0; + dec->priv->discont = TRUE; + dec->priv->sync_flush = FALSE; + + GST_OBJECT_UNLOCK (dec); +} + +static void +gst_base_audio_decoder_finalize (GObject * object) +{ + GstBaseAudioDecoder *dec; + + g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (object)); + dec = GST_BASE_AUDIO_DECODER (object); + + if (dec->priv->adapter) { + g_object_unref (dec->priv->adapter); + } + if (dec->priv->adapter_out) { + g_object_unref (dec->priv->adapter_out); + } + + G_OBJECT_CLASS (parent_class)->finalize (object); +} + +/* automagically perform sanity checking of src caps; + * also extracts output data format */ +static gboolean +gst_base_audio_decoder_src_setcaps (GstPad * pad, GstCaps * caps) +{ + GstBaseAudioDecoder *dec; + gboolean res = TRUE; + guint old_rate; + + dec = GST_BASE_AUDIO_DECODER (gst_pad_get_parent (pad)); + + GST_DEBUG_OBJECT (dec, "setting src caps %" GST_PTR_FORMAT, caps); + + /* parse caps here to check subclass; + * also makes us aware of output format */ + if (!gst_caps_is_fixed (caps)) + goto refuse_caps; + + /* adjust ts tracking to new sample rate */ + old_rate = GST_AUDIO_INFO_RATE (&dec->priv->ctx.info); + if (GST_CLOCK_TIME_IS_VALID (dec->priv->base_ts) && old_rate) { + dec->priv->base_ts += + GST_FRAMES_TO_CLOCK_TIME (dec->priv->samples, old_rate); + dec->priv->samples = 0; + } + + if (!gst_audio_info_from_caps (&dec->priv->ctx.info, caps)) + goto refuse_caps; + + gst_object_unref (dec); + return res; + + /* ERRORS */ +refuse_caps: + { + GST_WARNING_OBJECT (dec, "rejected caps %" GST_PTR_FORMAT, caps); + gst_object_unref (dec); + return res; + } +} + +static gboolean +gst_base_audio_decoder_sink_setcaps (GstPad * pad, GstCaps * caps) +{ + GstBaseAudioDecoder *dec; + GstBaseAudioDecoderClass *klass; + gboolean res = TRUE; + + dec = GST_BASE_AUDIO_DECODER (gst_pad_get_parent (pad)); + klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec); + + GST_DEBUG_OBJECT (dec, "caps: %" GST_PTR_FORMAT, caps); + + /* NOTE pbutils only needed here */ + /* TODO maybe (only) upstream demuxer/parser etc should handle this ? */ + if (dec->priv->taglist) + gst_tag_list_free (dec->priv->taglist); + dec->priv->taglist = gst_tag_list_new (); + gst_pb_utils_add_codec_description_to_tag_list (dec->priv->taglist, + GST_TAG_AUDIO_CODEC, caps); + + if (klass->set_format) + res = klass->set_format (dec, caps); + + g_object_unref (dec); + return res; +} + +static void +gst_base_audio_decoder_setup (GstBaseAudioDecoder * dec) +{ + GstQuery *query; + gboolean res; + + /* check if in live pipeline, then latency messing is no-no */ + query = gst_query_new_latency (); + res = gst_pad_peer_query (dec->sinkpad, query); + if (res) { + gst_query_parse_latency (query, &res, NULL, NULL); + res = !res; + } + gst_query_unref (query); + + /* normalize to bool */ + dec->priv->agg = !!res; +} + +/* mini aggregator combining output buffers into fewer larger ones, + * if so allowed/configured */ +static GstFlowReturn +gst_base_audio_decoder_output (GstBaseAudioDecoder * dec, GstBuffer * buf) +{ + GstBaseAudioDecoderClass *klass; + GstBaseAudioDecoderPrivate *priv; + GstBaseAudioDecoderContext *ctx; + GstFlowReturn ret = GST_FLOW_OK; + GstBuffer *inbuf = NULL; + + klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec); + priv = dec->priv; + ctx = &dec->priv->ctx; + + if (G_UNLIKELY (priv->agg < 0)) + gst_base_audio_decoder_setup (dec); + + if (G_LIKELY (buf)) { + g_return_val_if_fail (ctx->info.bpf != 0, GST_FLOW_ERROR); + + GST_LOG_OBJECT (dec, "output buffer of size %d with ts %" GST_TIME_FORMAT + ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buf), + GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)), + GST_TIME_ARGS (GST_BUFFER_DURATION (buf))); + + /* clip buffer */ + buf = gst_audio_buffer_clip (buf, &dec->segment, ctx->info.rate, + ctx->info.bpf); + if (G_UNLIKELY (!buf)) { + GST_DEBUG_OBJECT (dec, "no data after clipping to segment"); + } else { + GST_LOG_OBJECT (dec, + "buffer after segment clipping has size %d with ts %" GST_TIME_FORMAT + ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buf), + GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)), + GST_TIME_ARGS (GST_BUFFER_DURATION (buf))); + } + } else { + GST_DEBUG_OBJECT (dec, "no output buffer"); + } + +again: + inbuf = NULL; + if (priv->agg && dec->priv->latency > 0) { + gint av; + gboolean assemble = FALSE; + const GstClockTimeDiff tol = 10 * GST_MSECOND; + GstClockTimeDiff diff = -100 * GST_MSECOND; + + av = gst_adapter_available (priv->adapter_out); + if (G_UNLIKELY (!buf)) { + /* forcibly send current */ + assemble = TRUE; + GST_LOG_OBJECT (dec, "forcing fragment flush"); + } else if (av && (!GST_BUFFER_TIMESTAMP_IS_VALID (buf) || + !GST_CLOCK_TIME_IS_VALID (priv->out_ts) || + ((diff = GST_CLOCK_DIFF (GST_BUFFER_TIMESTAMP (buf), + priv->out_ts + priv->out_dur)) > tol) || diff < -tol)) { + assemble = TRUE; + GST_LOG_OBJECT (dec, "buffer %d ms apart from current fragment", + (gint) (diff / GST_MSECOND)); + } else { + /* add or start collecting */ + if (!av) { + GST_LOG_OBJECT (dec, "starting new fragment"); + priv->out_ts = GST_BUFFER_TIMESTAMP (buf); + } else { + GST_LOG_OBJECT (dec, "adding to fragment"); + } + gst_adapter_push (priv->adapter_out, buf); + priv->out_dur += GST_BUFFER_DURATION (buf); + av += GST_BUFFER_SIZE (buf); + buf = NULL; + } + if (priv->out_dur > dec->priv->latency) + assemble = TRUE; + if (av && assemble) { + GST_LOG_OBJECT (dec, "assembling fragment"); + inbuf = buf; + buf = gst_adapter_take_buffer (priv->adapter_out, av); + GST_BUFFER_TIMESTAMP (buf) = priv->out_ts; + GST_BUFFER_DURATION (buf) = priv->out_dur; + priv->out_ts = GST_CLOCK_TIME_NONE; + priv->out_dur = 0; + } + } + + if (G_LIKELY (buf)) { + + /* decorate */ + gst_buffer_set_caps (buf, GST_PAD_CAPS (dec->srcpad)); + + if (G_UNLIKELY (priv->discont)) { + GST_LOG_OBJECT (dec, "marking discont"); + GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT); + priv->discont = FALSE; + } + + if (G_LIKELY (GST_BUFFER_TIMESTAMP_IS_VALID (buf))) { + /* duration should always be valid for raw audio */ + g_assert (GST_BUFFER_DURATION_IS_VALID (buf)); + dec->segment.last_stop = + GST_BUFFER_TIMESTAMP (buf) + GST_BUFFER_DURATION (buf); + } + + if (klass->pre_push) { + /* last chance for subclass to do some dirty stuff */ + ret = klass->pre_push (dec, &buf); + if (ret != GST_FLOW_OK || !buf) { + GST_DEBUG_OBJECT (dec, "subclass returned %s, buf %p", + gst_flow_get_name (ret), buf); + if (buf) + gst_buffer_unref (buf); + goto exit; + } + } + + GST_LOG_OBJECT (dec, "pushing buffer of size %d with ts %" GST_TIME_FORMAT + ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buf), + GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)), + GST_TIME_ARGS (GST_BUFFER_DURATION (buf))); + + if (dec->segment.rate > 0.0) { + ret = gst_pad_push (dec->srcpad, buf); + GST_LOG_OBJECT (dec, "buffer pushed: %s", gst_flow_get_name (ret)); + } else { + ret = GST_FLOW_OK; + priv->queued = g_list_prepend (priv->queued, buf); + GST_LOG_OBJECT (dec, "buffer queued"); + } + + exit: + if (inbuf) { + buf = inbuf; + goto again; + } + } + + return ret; +} + +GstFlowReturn +gst_base_audio_decoder_finish_frame (GstBaseAudioDecoder * dec, GstBuffer * buf, + gint frames) +{ + GstBaseAudioDecoderPrivate *priv; + GstBaseAudioDecoderContext *ctx; + gint samples = 0; + GstClockTime ts, next_ts; + + /* subclass should know what it is producing by now */ + g_return_val_if_fail (buf == NULL || GST_PAD_CAPS (dec->srcpad) != NULL, + GST_FLOW_ERROR); + /* subclass should not hand us no data */ + g_return_val_if_fail (buf == NULL || GST_BUFFER_SIZE (buf) > 0, + GST_FLOW_ERROR); + /* no dummy calls please */ + g_return_val_if_fail (frames != 0, GST_FLOW_ERROR); + + priv = dec->priv; + ctx = &dec->priv->ctx; + + GST_LOG_OBJECT (dec, "accepting %d bytes == %d samples for %d frames", + buf ? GST_BUFFER_SIZE (buf) : -1, + buf ? GST_BUFFER_SIZE (buf) / ctx->info.bpf : -1, frames); + + /* output shoud be whole number of sample frames */ + if (G_LIKELY (buf && ctx->info.bpf)) { + if (GST_BUFFER_SIZE (buf) % ctx->info.bpf) + goto wrong_buffer; + /* per channel least */ + samples = GST_BUFFER_SIZE (buf) / ctx->info.bpf; + } + + /* frame and ts book-keeping */ + if (G_UNLIKELY (frames < 0)) { + if (G_UNLIKELY (-frames - 1 > priv->frames.length)) + goto overflow; + frames = priv->frames.length + frames + 1; + } else if (G_UNLIKELY (frames > priv->frames.length)) { + if (G_LIKELY (!priv->force)) { + /* no way we can let this pass */ + g_assert_not_reached (); + /* really no way */ + goto overflow; + } + } + + if (G_LIKELY (priv->frames.length)) + ts = GST_BUFFER_TIMESTAMP (priv->frames.head->data); + else + ts = GST_CLOCK_TIME_NONE; + + GST_DEBUG_OBJECT (dec, "leading frame ts %" GST_TIME_FORMAT, + GST_TIME_ARGS (ts)); + + while (priv->frames.length && frames) { + gst_buffer_unref (g_queue_pop_head (&priv->frames)); + dec->priv->ctx.delay = dec->priv->frames.length; + frames--; + } + + /* lock on */ + if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (priv->base_ts))) { + priv->base_ts = ts; + GST_DEBUG_OBJECT (dec, "base_ts now %" GST_TIME_FORMAT, GST_TIME_ARGS (ts)); + } + + if (G_UNLIKELY (!buf)) + goto exit; + + /* slightly convoluted approach caters for perfect ts if subclass desires */ + if (GST_CLOCK_TIME_IS_VALID (ts)) { + if (dec->priv->tolerance > 0) { + GstClockTimeDiff diff; + + g_assert (GST_CLOCK_TIME_IS_VALID (priv->base_ts)); + next_ts = priv->base_ts + + gst_util_uint64_scale (samples, GST_SECOND, ctx->info.rate); + GST_LOG_OBJECT (dec, "buffer is %d samples past base_ts %" GST_TIME_FORMAT + ", expected ts %" GST_TIME_FORMAT, samples, + GST_TIME_ARGS (priv->base_ts), GST_TIME_ARGS (next_ts)); + diff = GST_CLOCK_DIFF (next_ts, ts); + GST_LOG_OBJECT (dec, "ts diff %d ms", (gint) (diff / GST_MSECOND)); + /* if within tolerance, + * discard buffer ts and carry on producing perfect stream, + * otherwise resync to ts */ + if (G_UNLIKELY (diff < -dec->priv->tolerance || + diff > dec->priv->tolerance)) { + GST_DEBUG_OBJECT (dec, "base_ts resync"); + priv->base_ts = ts; + priv->samples = 0; + } + } else { + GST_DEBUG_OBJECT (dec, "base_ts resync"); + priv->base_ts = ts; + priv->samples = 0; + } + } + + /* delayed one-shot stuff until confirmed data */ + if (priv->taglist) { + GST_DEBUG_OBJECT (dec, "codec tag %" GST_PTR_FORMAT, priv->taglist); + if (gst_tag_list_is_empty (priv->taglist)) { + gst_tag_list_free (priv->taglist); + } else { + gst_element_found_tags (GST_ELEMENT (dec), priv->taglist); + } + priv->taglist = NULL; + } + + buf = gst_buffer_make_metadata_writable (buf); + if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (priv->base_ts))) { + GST_BUFFER_TIMESTAMP (buf) = + priv->base_ts + + GST_FRAMES_TO_CLOCK_TIME (priv->samples, ctx->info.rate); + GST_BUFFER_DURATION (buf) = priv->base_ts + + GST_FRAMES_TO_CLOCK_TIME (priv->samples + samples, ctx->info.rate) - + GST_BUFFER_TIMESTAMP (buf); + } else { + GST_BUFFER_TIMESTAMP (buf) = GST_CLOCK_TIME_NONE; + GST_BUFFER_DURATION (buf) = + GST_FRAMES_TO_CLOCK_TIME (samples, ctx->info.rate); + } + priv->samples += samples; + priv->samples_out += samples; + + /* we got data, so note things are looking up */ + if (G_UNLIKELY (dec->priv->error_count)) + dec->priv->error_count--; + +exit: + return gst_base_audio_decoder_output (dec, buf); + + /* ERRORS */ +wrong_buffer: + { + GST_ELEMENT_ERROR (dec, STREAM, ENCODE, (NULL), + ("buffer size %d not a multiple of %d", GST_BUFFER_SIZE (buf), + ctx->info.bpf)); + gst_buffer_unref (buf); + return GST_FLOW_ERROR; + } +overflow: + { + GST_ELEMENT_ERROR (dec, STREAM, ENCODE, + ("received more decoded frames %d than provided %d", frames, + priv->frames.length), (NULL)); + if (buf) + gst_buffer_unref (buf); + return GST_FLOW_ERROR; + } +} + +static GstFlowReturn +gst_base_audio_decoder_handle_frame (GstBaseAudioDecoder * dec, + GstBaseAudioDecoderClass * klass, GstBuffer * buffer) +{ + if (G_LIKELY (buffer)) { + /* keep around for admin */ + GST_LOG_OBJECT (dec, "tracking frame size %d, ts %" GST_TIME_FORMAT, + GST_BUFFER_SIZE (buffer), + GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer))); + g_queue_push_tail (&dec->priv->frames, buffer); + dec->priv->ctx.delay = dec->priv->frames.length; + dec->priv->bytes_in += GST_BUFFER_SIZE (buffer); + } else { + GST_LOG_OBJECT (dec, "providing subclass with NULL frame"); + } + + return klass->handle_frame (dec, buffer); +} + +/* maybe subclass configurable instead, but this allows for a whole lot of + * raw samples, so at least quite some encoded ... */ +#define GST_BASE_AUDIO_DECODER_MAX_SYNC 10 * 8 * 2 * 1024 + +static GstFlowReturn +gst_base_audio_decoder_push_buffers (GstBaseAudioDecoder * dec, gboolean force) +{ + GstBaseAudioDecoderClass *klass; + GstBaseAudioDecoderPrivate *priv; + GstBaseAudioDecoderContext *ctx; + GstFlowReturn ret = GST_FLOW_OK; + GstBuffer *buffer; + gint av, flush; + + klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec); + priv = dec->priv; + ctx = &dec->priv->ctx; + + g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR); + + av = gst_adapter_available (priv->adapter); + GST_DEBUG_OBJECT (dec, "available: %d", av); + + while (ret == GST_FLOW_OK) { + + flush = 0; + ctx->eos = force; + + if (G_LIKELY (av)) { + gint len; + GstClockTime ts; + + /* parse if needed */ + if (klass->parse) { + gint offset = 0; + + /* limited (legacy) parsing; avoid whole of baseparse */ + GST_DEBUG_OBJECT (dec, "parsing available: %d", av); + /* piggyback sync state on discont */ + ctx->sync = !priv->discont; + ret = klass->parse (dec, priv->adapter, &offset, &len); + + g_assert (offset <= av); + if (offset) { + /* jumped a bit */ + GST_DEBUG_OBJECT (dec, "setting DISCONT"); + gst_adapter_flush (priv->adapter, offset); + flush = offset; + /* avoid parsing indefinitely */ + priv->sync_flush += offset; + if (priv->sync_flush > GST_BASE_AUDIO_DECODER_MAX_SYNC) + goto parse_failed; + } + + if (ret == GST_FLOW_UNEXPECTED) { + GST_LOG_OBJECT (dec, "no frame yet"); + ret = GST_FLOW_OK; + break; + } else if (ret == GST_FLOW_OK) { + GST_LOG_OBJECT (dec, "frame at offset %d of length %d", offset, len); + g_assert (offset + len <= av); + priv->sync_flush = 0; + } else { + break; + } + } else { + len = av; + } + /* track upstream ts, but do not get stuck if nothing new upstream */ + ts = gst_adapter_prev_timestamp (priv->adapter, NULL); + if (ts == priv->prev_ts) { + GST_LOG_OBJECT (dec, "ts == prev_ts; discarding"); + ts = GST_CLOCK_TIME_NONE; + } else { + priv->prev_ts = ts; + } + buffer = gst_adapter_take_buffer (priv->adapter, len); + buffer = gst_buffer_make_metadata_writable (buffer); + GST_BUFFER_TIMESTAMP (buffer) = ts; + flush += len; + } else { + if (!force) + break; + buffer = NULL; + } + + ret = gst_base_audio_decoder_handle_frame (dec, klass, buffer); + + /* do not keep pushing it ... */ + if (G_UNLIKELY (!av)) { + priv->drained = TRUE; + break; + } + + av -= flush; + g_assert (av >= 0); + } + + GST_LOG_OBJECT (dec, "done pushing to subclass"); + return ret; + + /* ERRORS */ +parse_failed: + { + GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL), ("failed to parse stream")); + return GST_FLOW_ERROR; + } +} + +static GstFlowReturn +gst_base_audio_decoder_drain (GstBaseAudioDecoder * dec) +{ + GstFlowReturn ret; + + if (dec->priv->drained) + return GST_FLOW_OK; + else { + /* dispatch reverse pending buffers */ + /* chain eventually calls upon drain as well, but by that time + * gather list should be clear, so ok ... */ + if (dec->segment.rate < 0.0 && dec->priv->gather) + gst_base_audio_decoder_chain_reverse (dec, NULL); + /* have subclass give all it can */ + ret = gst_base_audio_decoder_push_buffers (dec, TRUE); + /* ensure all output sent */ + ret = gst_base_audio_decoder_output (dec, NULL); + /* everything should be away now */ + if (dec->priv->frames.length) { + /* not fatal/impossible though if subclass/codec eats stuff */ + GST_WARNING_OBJECT (dec, "still %d frames left after draining", + dec->priv->frames.length); + g_queue_foreach (&dec->priv->frames, (GFunc) gst_buffer_unref, NULL); + g_queue_clear (&dec->priv->frames); + } + /* discard (unparsed) leftover */ + gst_adapter_clear (dec->priv->adapter); + + return ret; + } +} + +/* hard == FLUSH, otherwise discont */ +static GstFlowReturn +gst_base_audio_decoder_flush (GstBaseAudioDecoder * dec, gboolean hard) +{ + GstBaseAudioDecoderClass *klass; + GstFlowReturn ret = GST_FLOW_OK; + + klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec); + + GST_LOG_OBJECT (dec, "flush hard %d", hard); + + if (!hard) { + ret = gst_base_audio_decoder_drain (dec); + } else { + gst_base_audio_decoder_clear_queues (dec); + gst_segment_init (&dec->segment, GST_FORMAT_TIME); + dec->priv->error_count = 0; + } + /* only bother subclass with flushing if known it is already alive + * and kicking out stuff */ + if (klass->flush && dec->priv->samples_out > 0) + klass->flush (dec, hard); + /* and get (re)set for the sequel */ + gst_base_audio_decoder_reset (dec, FALSE); + + return ret; +} + +static GstFlowReturn +gst_base_audio_decoder_chain_forward (GstBaseAudioDecoder * dec, + GstBuffer * buffer) +{ + GstFlowReturn ret; + + /* grab buffer */ + gst_adapter_push (dec->priv->adapter, buffer); + buffer = NULL; + /* new stuff, so we can push subclass again */ + dec->priv->drained = FALSE; + + /* hand to subclass */ + ret = gst_base_audio_decoder_push_buffers (dec, FALSE); + + GST_LOG_OBJECT (dec, "chain-done"); + return ret; +} + +static void +gst_base_audio_decoder_clear_queues (GstBaseAudioDecoder * dec) +{ + GstBaseAudioDecoderPrivate *priv = dec->priv; + + g_list_foreach (priv->queued, (GFunc) gst_mini_object_unref, NULL); + g_list_free (priv->queued); + priv->queued = NULL; + g_list_foreach (priv->gather, (GFunc) gst_mini_object_unref, NULL); + g_list_free (priv->gather); + priv->gather = NULL; + g_list_foreach (priv->decode, (GFunc) gst_mini_object_unref, NULL); + g_list_free (priv->decode); + priv->decode = NULL; +} + +/* + * Input: + * Buffer decoding order: 7 8 9 4 5 6 3 1 2 EOS + * Discont flag: D D D D + * + * - Each Discont marks a discont in the decoding order. + * + * for vorbis, each buffer is a keyframe when we have the previous + * buffer. This means that to decode buffer 7, we need buffer 6, which + * arrives out of order. + * + * we first gather buffers in the gather queue until we get a DISCONT. We + * prepend each incomming buffer so that they are in reversed order. + * + * gather queue: 9 8 7 + * decode queue: + * output queue: + * + * When a DISCONT is received (buffer 4), we move the gather queue to the + * decode queue. This is simply done be taking the head of the gather queue + * and prepending it to the decode queue. This yields: + * + * gather queue: + * decode queue: 7 8 9 + * output queue: + * + * Then we decode each buffer in the decode queue in order and put the output + * buffer in the output queue. The first buffer (7) will not produce any output + * because it needs the previous buffer (6) which did not arrive yet. This + * yields: + * + * gather queue: + * decode queue: 7 8 9 + * output queue: 9 8 + * + * Then we remove the consumed buffers from the decode queue. Buffer 7 is not + * completely consumed, we need to keep it around for when we receive buffer + * 6. This yields: + * + * gather queue: + * decode queue: 7 + * output queue: 9 8 + * + * Then we accumulate more buffers: + * + * gather queue: 6 5 4 + * decode queue: 7 + * output queue: + * + * prepending to the decode queue on DISCONT yields: + * + * gather queue: + * decode queue: 4 5 6 7 + * output queue: + * + * after decoding and keeping buffer 4: + * + * gather queue: + * decode queue: 4 + * output queue: 7 6 5 + * + * Etc.. + */ +static GstFlowReturn +gst_base_audio_decoder_flush_decode (GstBaseAudioDecoder * dec) +{ + GstBaseAudioDecoderPrivate *priv = dec->priv; + GstFlowReturn res = GST_FLOW_OK; + GList *walk; + + walk = priv->decode; + + GST_DEBUG_OBJECT (dec, "flushing buffers to decoder"); + + /* clear buffer and decoder state */ + gst_base_audio_decoder_flush (dec, FALSE); + + while (walk) { + GList *next; + GstBuffer *buf = GST_BUFFER_CAST (walk->data); + + GST_DEBUG_OBJECT (dec, "decoding buffer %p, ts %" GST_TIME_FORMAT, + buf, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf))); + + next = g_list_next (walk); + /* decode buffer, resulting data prepended to output queue */ + gst_buffer_ref (buf); + res = gst_base_audio_decoder_chain_forward (dec, buf); + + /* if we generated output, we can discard the buffer, else we + * keep it in the queue */ + if (priv->queued) { + GST_DEBUG_OBJECT (dec, "decoded buffer to %p", priv->queued->data); + priv->decode = g_list_delete_link (priv->decode, walk); + gst_buffer_unref (buf); + } else { + GST_DEBUG_OBJECT (dec, "buffer did not decode, keeping"); + } + walk = next; + } + + /* drain any aggregation (or otherwise) leftover */ + gst_base_audio_decoder_drain (dec); + + /* now send queued data downstream */ + while (priv->queued) { + GstBuffer *buf = GST_BUFFER_CAST (priv->queued->data); + + if (G_LIKELY (res == GST_FLOW_OK)) { + GST_DEBUG_OBJECT (dec, "pushing buffer %p of size %u, " + "time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT, buf, + GST_BUFFER_SIZE (buf), GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)), + GST_TIME_ARGS (GST_BUFFER_DURATION (buf))); + /* should be already, but let's be sure */ + buf = gst_buffer_make_metadata_writable (buf); + /* avoid stray DISCONT from forward processing, + * which have no meaning in reverse pushing */ + GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT); + res = gst_pad_push (dec->srcpad, buf); + } else { + gst_buffer_unref (buf); + } + + priv->queued = g_list_delete_link (priv->queued, priv->queued); + } + + return res; +} + +static GstFlowReturn +gst_base_audio_decoder_chain_reverse (GstBaseAudioDecoder * dec, + GstBuffer * buf) +{ + GstBaseAudioDecoderPrivate *priv = dec->priv; + GstFlowReturn result = GST_FLOW_OK; + + /* if we have a discont, move buffers to the decode list */ + if (!buf || GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT)) { + GST_DEBUG_OBJECT (dec, "received discont"); + while (priv->gather) { + GstBuffer *gbuf; + + gbuf = GST_BUFFER_CAST (priv->gather->data); + /* remove from the gather list */ + priv->gather = g_list_delete_link (priv->gather, priv->gather); + /* copy to decode queue */ + priv->decode = g_list_prepend (priv->decode, gbuf); + } + /* decode stuff in the decode queue */ + gst_base_audio_decoder_flush_decode (dec); + } + + if (G_LIKELY (buf)) { + GST_DEBUG_OBJECT (dec, "gathering buffer %p of size %u, " + "time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT, buf, + GST_BUFFER_SIZE (buf), GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)), + GST_TIME_ARGS (GST_BUFFER_DURATION (buf))); + + /* add buffer to gather queue */ + priv->gather = g_list_prepend (priv->gather, buf); + } + + return result; +} + +static GstFlowReturn +gst_base_audio_decoder_chain (GstPad * pad, GstBuffer * buffer) +{ + GstBaseAudioDecoder *dec; + GstFlowReturn ret; + + dec = GST_BASE_AUDIO_DECODER (GST_PAD_PARENT (pad)); + + GST_LOG_OBJECT (dec, + "received buffer of size %d with ts %" GST_TIME_FORMAT + ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer), + GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)), + GST_TIME_ARGS (GST_BUFFER_DURATION (buffer))); + + if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT)) { + gint64 samples, ts; + + /* track present position */ + ts = dec->priv->base_ts; + samples = dec->priv->samples; + + GST_DEBUG_OBJECT (dec, "handling discont"); + gst_base_audio_decoder_flush (dec, FALSE); + dec->priv->discont = TRUE; + + /* buffer may claim DISCONT loudly, if it can't tell us where we are now, + * we'll stick to where we were ... + * Particularly useful/needed for upstream BYTE based */ + if (dec->segment.rate > 0.0 && !GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) { + GST_DEBUG_OBJECT (dec, "... but restoring previous ts tracking"); + dec->priv->base_ts = ts; + dec->priv->samples = samples; + } + } + + if (dec->segment.rate > 0.0) + ret = gst_base_audio_decoder_chain_forward (dec, buffer); + else + ret = gst_base_audio_decoder_chain_reverse (dec, buffer); + + return ret; +} + +/* perform upstream byte <-> time conversion (duration, seeking) + * if subclass allows and if enough data for moderately decent conversion */ +static inline gboolean +gst_base_audio_decoder_do_byte (GstBaseAudioDecoder * dec) +{ + return dec->priv->ctx.do_byte_time && dec->priv->ctx.info.bpf && + dec->priv->ctx.info.rate <= dec->priv->samples_out; +} + +static gboolean +gst_base_audio_decoder_sink_eventfunc (GstBaseAudioDecoder * dec, + GstEvent * event) +{ + gboolean handled = FALSE; + + switch (GST_EVENT_TYPE (event)) { + case GST_EVENT_NEWSEGMENT: + { + GstFormat format; + gdouble rate, arate; + gint64 start, stop, time; + gboolean update; + + gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format, + &start, &stop, &time); + + if (format == GST_FORMAT_TIME) { + GST_DEBUG_OBJECT (dec, "received TIME NEW_SEGMENT %" GST_TIME_FORMAT + " -- %" GST_TIME_FORMAT ", time %" GST_TIME_FORMAT + ", rate %g, applied_rate %g", + GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (time), + rate, arate); + } else { + GstFormat dformat = GST_FORMAT_TIME; + + GST_DEBUG_OBJECT (dec, "received NEW_SEGMENT %" G_GINT64_FORMAT + " -- %" G_GINT64_FORMAT ", time %" G_GINT64_FORMAT + ", rate %g, applied_rate %g", start, stop, time, rate, arate); + /* handle newsegment resulting from legacy simple seeking */ + /* note that we need to convert this whether or not enough data + * to handle initial newsegment */ + if (dec->priv->ctx.do_byte_time && + gst_pad_query_convert (dec->sinkpad, GST_FORMAT_BYTES, start, + &dformat, &start)) { + /* best attempt convert */ + /* as these are only estimates, stop is kept open-ended to avoid + * premature cutting */ + GST_DEBUG_OBJECT (dec, "converted to TIME start %" GST_TIME_FORMAT, + GST_TIME_ARGS (start)); + format = GST_FORMAT_TIME; + time = start; + stop = GST_CLOCK_TIME_NONE; + /* replace event */ + gst_event_unref (event); + event = gst_event_new_new_segment_full (update, rate, arate, + GST_FORMAT_TIME, start, stop, time); + } else { + GST_DEBUG_OBJECT (dec, "unsupported format; ignoring"); + break; + } + } + + /* finish current segment */ + gst_base_audio_decoder_drain (dec); + + if (update) { + /* time progressed without data, see if we can fill the gap with + * some concealment data */ + GST_DEBUG_OBJECT (dec, + "segment update: plc %d, do_plc %d, last_stop %" GST_TIME_FORMAT, + dec->priv->plc, dec->priv->ctx.do_plc, + GST_TIME_ARGS (dec->segment.last_stop)); + if (dec->priv->plc && dec->priv->ctx.do_plc && + dec->segment.rate > 0.0 && dec->segment.last_stop < start) { + GstBaseAudioDecoderClass *klass; + GstBuffer *buf; + + klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec); + /* hand subclass empty frame with duration that needs covering */ + buf = gst_buffer_new (); + GST_BUFFER_DURATION (buf) = start - dec->segment.last_stop; + /* best effort, not much error handling */ + gst_base_audio_decoder_handle_frame (dec, klass, buf); + } + } else { + /* prepare for next one */ + gst_base_audio_decoder_flush (dec, FALSE); + /* and that's where we time from, + * in case upstream does not come up with anything better + * (e.g. upstream BYTE) */ + if (format != GST_FORMAT_TIME) { + dec->priv->base_ts = start; + dec->priv->samples = 0; + } + } + + /* and follow along with segment */ + gst_segment_set_newsegment_full (&dec->segment, update, rate, arate, + format, start, stop, time); + + gst_pad_push_event (dec->srcpad, event); + handled = TRUE; + break; + } + + case GST_EVENT_FLUSH_START: + break; + + case GST_EVENT_FLUSH_STOP: + /* prepare for fresh start */ + gst_base_audio_decoder_flush (dec, TRUE); + break; + + case GST_EVENT_EOS: + gst_base_audio_decoder_drain (dec); + break; + + default: + break; + } + + return handled; +} + +static gboolean +gst_base_audio_decoder_sink_event (GstPad * pad, GstEvent * event) +{ + GstBaseAudioDecoder *dec; + GstBaseAudioDecoderClass *klass; + gboolean handled = FALSE; + gboolean ret = TRUE; + + dec = GST_BASE_AUDIO_DECODER (gst_pad_get_parent (pad)); + klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec); + + GST_DEBUG_OBJECT (dec, "received event %d, %s", GST_EVENT_TYPE (event), + GST_EVENT_TYPE_NAME (event)); + + if (klass->event) + handled = klass->event (dec, event); + + if (!handled) + handled = gst_base_audio_decoder_sink_eventfunc (dec, event); + + if (!handled) + ret = gst_pad_event_default (pad, event); + + GST_DEBUG_OBJECT (dec, "event handled"); + + gst_object_unref (dec); + return ret; +} + +static gboolean +gst_base_audio_decoder_do_seek (GstBaseAudioDecoder * dec, GstEvent * event) +{ + GstSeekFlags flags; + GstSeekType start_type, end_type; + GstFormat format; + gdouble rate; + gint64 start, start_time, end_time; + GstSegment seek_segment; + guint32 seqnum; + + gst_event_parse_seek (event, &rate, &format, &flags, &start_type, + &start_time, &end_type, &end_time); + + /* we'll handle plain open-ended flushing seeks with the simple approach */ + if (rate != 1.0) { + GST_DEBUG_OBJECT (dec, "unsupported seek: rate"); + return FALSE; + } + + if (start_type != GST_SEEK_TYPE_SET) { + GST_DEBUG_OBJECT (dec, "unsupported seek: start time"); + return FALSE; + } + + if (end_type != GST_SEEK_TYPE_NONE || + (end_type == GST_SEEK_TYPE_SET && end_time != GST_CLOCK_TIME_NONE)) { + GST_DEBUG_OBJECT (dec, "unsupported seek: end time"); + return FALSE; + } + + if (!(flags & GST_SEEK_FLAG_FLUSH)) { + GST_DEBUG_OBJECT (dec, "unsupported seek: not flushing"); + return FALSE; + } + + memcpy (&seek_segment, &dec->segment, sizeof (seek_segment)); + gst_segment_set_seek (&seek_segment, rate, format, flags, start_type, + start_time, end_type, end_time, NULL); + start_time = seek_segment.last_stop; + + format = GST_FORMAT_BYTES; + if (!gst_pad_query_convert (dec->sinkpad, GST_FORMAT_TIME, start_time, + &format, &start)) { + GST_DEBUG_OBJECT (dec, "conversion failed"); + return FALSE; + } + + seqnum = gst_event_get_seqnum (event); + event = gst_event_new_seek (1.0, GST_FORMAT_BYTES, flags, + GST_SEEK_TYPE_SET, start, GST_SEEK_TYPE_NONE, -1); + gst_event_set_seqnum (event, seqnum); + + GST_DEBUG_OBJECT (dec, "seeking to %" GST_TIME_FORMAT " at byte offset %" + G_GINT64_FORMAT, GST_TIME_ARGS (start_time), start); + + return gst_pad_push_event (dec->sinkpad, event); +} + +static gboolean +gst_base_audio_decoder_src_event (GstPad * pad, GstEvent * event) +{ + GstBaseAudioDecoder *dec; + gboolean res = FALSE; + + dec = GST_BASE_AUDIO_DECODER (gst_pad_get_parent (pad)); + + GST_DEBUG_OBJECT (dec, "received event %d, %s", GST_EVENT_TYPE (event), + GST_EVENT_TYPE_NAME (event)); + + switch (GST_EVENT_TYPE (event)) { + case GST_EVENT_SEEK: + { + GstFormat format, tformat; + gdouble rate; + GstSeekFlags flags; + GstSeekType cur_type, stop_type; + gint64 cur, stop; + gint64 tcur, tstop; + guint32 seqnum; + + gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur, + &stop_type, &stop); + seqnum = gst_event_get_seqnum (event); + + /* upstream gets a chance first */ + if ((res = gst_pad_push_event (dec->sinkpad, event))) + break; + + /* if upstream fails for a time seek, maybe we can help if allowed */ + if (format == GST_FORMAT_TIME) { + if (gst_base_audio_decoder_do_byte (dec)) + res = gst_base_audio_decoder_do_seek (dec, event); + break; + } + + /* ... though a non-time seek can be aided as well */ + /* First bring the requested format to time */ + tformat = GST_FORMAT_TIME; + if (!(res = gst_pad_query_convert (pad, format, cur, &tformat, &tcur))) + goto convert_error; + if (!(res = gst_pad_query_convert (pad, format, stop, &tformat, &tstop))) + goto convert_error; + + /* then seek with time on the peer */ + event = gst_event_new_seek (rate, GST_FORMAT_TIME, + flags, cur_type, tcur, stop_type, tstop); + gst_event_set_seqnum (event, seqnum); + + res = gst_pad_push_event (dec->sinkpad, event); + break; + } + default: + res = gst_pad_push_event (dec->sinkpad, event); + break; + } +done: + gst_object_unref (dec); + + return res; + + /* ERRORS */ +convert_error: + { + GST_DEBUG_OBJECT (dec, "cannot convert start/stop for seek"); + goto done; + } +} + +/* + * gst_base_audio_encoded_audio_convert: + * @fmt: audio format of the encoded audio + * @bytes: number of encoded bytes + * @samples: number of encoded samples + * @src_format: source format + * @src_value: source value + * @dest_format: destination format + * @dest_value: destination format + * + * Helper function to convert @src_value in @src_format to @dest_value in + * @dest_format for encoded audio data. Conversion is possible between + * BYTE and TIME format by using estimated bitrate based on + * @samples and @bytes (and @fmt). + */ +/* FIXME: make gst_base_audio_encoded_audio_convert() public? */ +static gboolean +gst_base_audio_encoded_audio_convert (GstAudioInfo * fmt, + gint64 bytes, gint64 samples, GstFormat src_format, + gint64 src_value, GstFormat * dest_format, gint64 * dest_value) +{ + gboolean res = FALSE; + + g_return_val_if_fail (dest_format != NULL, FALSE); + g_return_val_if_fail (dest_value != NULL, FALSE); + + if (G_UNLIKELY (src_format == *dest_format || src_value == 0 || + src_value == -1)) { + if (dest_value) + *dest_value = src_value; + return TRUE; + } + + if (samples == 0 || bytes == 0 || fmt->rate == 0) { + GST_DEBUG ("not enough metadata yet to convert"); + goto exit; + } + + bytes *= fmt->rate; + + switch (src_format) { + case GST_FORMAT_BYTES: + switch (*dest_format) { + case GST_FORMAT_TIME: + *dest_value = gst_util_uint64_scale (src_value, + GST_SECOND * samples, bytes); + res = TRUE; + break; + default: + res = FALSE; + } + break; + case GST_FORMAT_TIME: + switch (*dest_format) { + case GST_FORMAT_BYTES: + *dest_value = gst_util_uint64_scale (src_value, bytes, + samples * GST_SECOND); + res = TRUE; + break; + default: + res = FALSE; + } + break; + default: + res = FALSE; + } + +exit: + return res; +} + +static gboolean +gst_base_audio_decoder_sink_query (GstPad * pad, GstQuery * query) +{ + gboolean res = TRUE; + GstBaseAudioDecoder *dec; + + dec = GST_BASE_AUDIO_DECODER (gst_pad_get_parent (pad)); + + switch (GST_QUERY_TYPE (query)) { + case GST_QUERY_FORMATS: + { + gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES); + res = TRUE; + break; + } + case GST_QUERY_CONVERT: + { + GstFormat src_fmt, dest_fmt; + gint64 src_val, dest_val; + + gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val); + if (!(res = gst_base_audio_encoded_audio_convert (&dec->priv->ctx.info, + dec->priv->bytes_in, dec->priv->samples_out, + src_fmt, src_val, &dest_fmt, &dest_val))) + goto error; + gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val); + break; + } + default: + res = gst_pad_query_default (pad, query); + break; + } + +error: + gst_object_unref (dec); + return res; +} + +static const GstQueryType * +gst_base_audio_decoder_get_query_types (GstPad * pad) +{ + static const GstQueryType gst_base_audio_decoder_src_query_types[] = { + GST_QUERY_POSITION, + GST_QUERY_DURATION, + GST_QUERY_CONVERT, + GST_QUERY_LATENCY, + 0 + }; + + return gst_base_audio_decoder_src_query_types; +} + +/* FIXME ? are any of these queries (other than latency) a decoder's business ?? + * also, the conversion stuff might seem to make sense, but seems to not mind + * segment stuff etc at all + * Supposedly that's backward compatibility ... */ +static gboolean +gst_base_audio_decoder_src_query (GstPad * pad, GstQuery * query) +{ + GstBaseAudioDecoder *dec; + GstPad *peerpad; + gboolean res = FALSE; + + dec = GST_BASE_AUDIO_DECODER (GST_PAD_PARENT (pad)); + peerpad = gst_pad_get_peer (GST_PAD (dec->sinkpad)); + + GST_LOG_OBJECT (dec, "handling query: %" GST_PTR_FORMAT, query); + + switch (GST_QUERY_TYPE (query)) { + case GST_QUERY_DURATION: + { + GstFormat format; + + /* upstream in any case */ + if ((res = gst_pad_query_default (pad, query))) + break; + + gst_query_parse_duration (query, &format, NULL); + /* try answering TIME by converting from BYTE if subclass allows */ + if (format == GST_FORMAT_TIME && gst_base_audio_decoder_do_byte (dec)) { + gint64 value; + + format = GST_FORMAT_BYTES; + if (gst_pad_query_peer_duration (dec->sinkpad, &format, &value)) { + GST_LOG_OBJECT (dec, "upstream size %" G_GINT64_FORMAT, value); + format = GST_FORMAT_TIME; + if (gst_pad_query_convert (dec->sinkpad, GST_FORMAT_BYTES, value, + &format, &value)) { + gst_query_set_duration (query, GST_FORMAT_TIME, value); + res = TRUE; + } + } + } + break; + } + case GST_QUERY_POSITION: + { + GstFormat format; + gint64 time, value; + + if ((res = gst_pad_peer_query (dec->sinkpad, query))) { + GST_LOG_OBJECT (dec, "returning peer response"); + break; + } + + /* we start from the last seen time */ + time = dec->segment.last_stop; + /* correct for the segment values */ + time = gst_segment_to_stream_time (&dec->segment, GST_FORMAT_TIME, time); + + GST_LOG_OBJECT (dec, + "query %p: our time: %" GST_TIME_FORMAT, query, GST_TIME_ARGS (time)); + + /* and convert to the final format */ + gst_query_parse_position (query, &format, NULL); + if (!(res = gst_pad_query_convert (pad, GST_FORMAT_TIME, time, + &format, &value))) + break; + + gst_query_set_position (query, format, value); + + GST_LOG_OBJECT (dec, + "query %p: we return %" G_GINT64_FORMAT " (format %u)", query, value, + format); + break; + } + case GST_QUERY_FORMATS: + { + gst_query_set_formats (query, 3, + GST_FORMAT_TIME, GST_FORMAT_BYTES, GST_FORMAT_DEFAULT); + res = TRUE; + break; + } + case GST_QUERY_CONVERT: + { + GstFormat src_fmt, dest_fmt; + gint64 src_val, dest_val; + + gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val); + if (!(res = gst_audio_info_convert (&dec->priv->ctx.info, + src_fmt, src_val, dest_fmt, &dest_val))) + break; + gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val); + break; + } + case GST_QUERY_LATENCY: + { + if ((res = gst_pad_peer_query (dec->sinkpad, query))) { + gboolean live; + GstClockTime min_latency, max_latency; + + gst_query_parse_latency (query, &live, &min_latency, &max_latency); + GST_DEBUG_OBJECT (dec, "Peer latency: live %d, min %" + GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live, + GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency)); + + GST_OBJECT_LOCK (dec); + /* add our latency */ + if (min_latency != -1) + min_latency += dec->priv->ctx.min_latency; + if (max_latency != -1) + max_latency += dec->priv->ctx.max_latency; + GST_OBJECT_UNLOCK (dec); + + gst_query_set_latency (query, live, min_latency, max_latency); + } + break; + } + default: + res = gst_pad_query_default (pad, query); + break; + } + + gst_object_unref (peerpad); + return res; +} + +static gboolean +gst_base_audio_decoder_stop (GstBaseAudioDecoder * dec) +{ + GstBaseAudioDecoderClass *klass; + gboolean ret = TRUE; + + GST_DEBUG_OBJECT (dec, "gst_base_audio_decoder_stop"); + + klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec); + + if (klass->stop) { + ret = klass->stop (dec); + } + + /* clean up */ + gst_base_audio_decoder_reset (dec, TRUE); + + if (ret) + dec->priv->active = FALSE; + + return TRUE; +} + +static gboolean +gst_base_audio_decoder_start (GstBaseAudioDecoder * dec) +{ + GstBaseAudioDecoderClass *klass; + gboolean ret = TRUE; + + GST_DEBUG_OBJECT (dec, "gst_base_audio_decoder_start"); + + klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec); + + /* arrange clean state */ + gst_base_audio_decoder_reset (dec, TRUE); + + if (klass->start) { + ret = klass->start (dec); + } + + if (ret) + dec->priv->active = TRUE; + + return TRUE; +} + +static void +gst_base_audio_decoder_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec) +{ + GstBaseAudioDecoder *dec; + + dec = GST_BASE_AUDIO_DECODER (object); + + switch (prop_id) { + case PROP_LATENCY: + g_value_set_int64 (value, dec->priv->latency); + break; + case PROP_TOLERANCE: + g_value_set_int64 (value, dec->priv->tolerance); + break; + case PROP_PLC: + g_value_set_boolean (value, dec->priv->plc); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_base_audio_decoder_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstBaseAudioDecoder *dec; + + dec = GST_BASE_AUDIO_DECODER (object); + + switch (prop_id) { + case PROP_LATENCY: + dec->priv->latency = g_value_get_int64 (value); + break; + case PROP_TOLERANCE: + dec->priv->tolerance = g_value_get_int64 (value); + break; + case PROP_PLC: + dec->priv->plc = g_value_get_boolean (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static GstStateChangeReturn +gst_base_audio_decoder_change_state (GstElement * element, + GstStateChange transition) +{ + GstBaseAudioDecoder *codec; + GstStateChangeReturn ret; + + codec = GST_BASE_AUDIO_DECODER (element); + + switch (transition) { + case GST_STATE_CHANGE_NULL_TO_READY: + break; + case GST_STATE_CHANGE_READY_TO_PAUSED: + if (!gst_base_audio_decoder_start (codec)) { + goto start_failed; + } + break; + case GST_STATE_CHANGE_PAUSED_TO_PLAYING: + break; + default: + break; + } + + ret = parent_class->change_state (element, transition); + + switch (transition) { + case GST_STATE_CHANGE_PLAYING_TO_PAUSED: + break; + case GST_STATE_CHANGE_PAUSED_TO_READY: + if (!gst_base_audio_decoder_stop (codec)) { + goto stop_failed; + } + break; + case GST_STATE_CHANGE_READY_TO_NULL: + break; + default: + break; + } + + return ret; + +start_failed: + { + GST_ELEMENT_ERROR (codec, LIBRARY, INIT, (NULL), ("Failed to start codec")); + return GST_STATE_CHANGE_FAILURE; + } +stop_failed: + { + GST_ELEMENT_ERROR (codec, LIBRARY, INIT, (NULL), ("Failed to stop codec")); + return GST_STATE_CHANGE_FAILURE; + } +} + +GstFlowReturn +_gst_base_audio_decoder_error (GstBaseAudioDecoder * dec, gint weight, + GQuark domain, gint code, gchar * txt, gchar * dbg, const gchar * file, + const gchar * function, gint line) +{ + if (txt) + GST_WARNING_OBJECT (dec, "error: %s", txt); + if (dbg) + GST_WARNING_OBJECT (dec, "error: %s", dbg); + dec->priv->error_count += weight; + dec->priv->discont = TRUE; + if (dec->priv->ctx.max_errors < dec->priv->error_count) { + gst_element_message_full (GST_ELEMENT (dec), GST_MESSAGE_ERROR, + domain, code, txt, dbg, file, function, line); + return GST_FLOW_ERROR; + } else { + return GST_FLOW_OK; + } +} + +/** + * gst_base_audio_decoder_get_audio_info: + * @dec: a #GstBaseAudioDecoder + * + * Returns: a #GstAudioInfo describing the input audio format + * + * Since: 0.10.36 + */ +GstAudioInfo * +gst_base_audio_decoder_get_audio_info (GstBaseAudioDecoder * dec) +{ + g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), NULL); + + return &dec->priv->ctx.info; +} + +/** + * gst_base_audio_decoder_set_plc_aware: + * @dec: a #GstBaseAudioDecoder + * @plc: new plc state + * + * Indicates whether or not subclass handles packet loss concealment (plc). + * + * Since: 0.10.36 + */ +void +gst_base_audio_decoder_set_plc_aware (GstBaseAudioDecoder * dec, gboolean plc) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec)); + + dec->priv->ctx.do_plc = plc; +} + +/** + * gst_base_audio_decoder_get_plc_aware: + * @dec: a #GstBaseAudioDecoder + * + * Returns: currently configured plc handling + * + * Since: 0.10.36 + */ +gint +gst_base_audio_decoder_get_plc_aware (GstBaseAudioDecoder * dec) +{ + g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), 0); + + return dec->priv->ctx.do_plc; +} + +/** + * gst_base_audio_decoder_set_byte_time: + * @dec: a #GstBaseAudioDecoder + * @enabled: whether to enable byte to time conversion + * + * Allows baseclass to perform byte to time estimated conversion. + * + * Since: 0.10.36 + */ +void +gst_base_audio_decoder_set_byte_time (GstBaseAudioDecoder * dec, + gboolean enabled) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec)); + + dec->priv->ctx.do_byte_time = enabled; +} + +/** + * gst_base_audio_decoder_get_byte_time: + * @dec: a #GstBaseAudioDecoder + * + * Returns: currently configured byte to time conversion setting + * + * Since: 0.10.36 + */ +gint +gst_base_audio_decoder_get_byte_time (GstBaseAudioDecoder * dec) +{ + g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), 0); + + return dec->priv->ctx.do_byte_time; +} + +/** + * gst_base_audio_decoder_get_delay: + * @dec: a #GstBaseAudioDecoder + * + * Returns: currently configured decoder delay + * + * Since: 0.10.36 + */ +gint +gst_base_audio_decoder_get_delay (GstBaseAudioDecoder * dec) +{ + g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), 0); + + return dec->priv->ctx.delay; +} + +/** + * gst_base_audio_decoder_set_max_errors: + * @dec: a #GstBaseAudioDecoder + * @num: max tolerated errors + * + * Sets numbers of tolerated decoder errors, where a tolerated one is then only + * warned about, but more than tolerated will lead to fatal error. + * + * Since: 0.10.36 + */ +void +gst_base_audio_decoder_set_max_errors (GstBaseAudioDecoder * enc, gint num) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (enc)); + + enc->priv->ctx.max_errors = num; +} + +/** + * gst_base_audio_decoder_get_max_errors: + * @dec: a #GstBaseAudioDecoder + * + * Returns: currently configured decoder tolerated error count. + * + * Since: 0.10.36 + */ +gint +gst_base_audio_decoder_get_max_errors (GstBaseAudioDecoder * dec) +{ + g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), 0); + + return dec->priv->ctx.max_errors; +} + +/** + * gst_base_audio_decoder_set_latency: + * @dec: a #GstBaseAudioDecoder + * @min: minimum latency + * @max: maximum latency + * + * Sets decoder latency. + * + * Since: 0.10.36 + */ +void +gst_base_audio_decoder_set_latency (GstBaseAudioDecoder * dec, + GstClockTime min, GstClockTime max) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec)); + + GST_OBJECT_LOCK (dec); + dec->priv->ctx.min_latency = min; + dec->priv->ctx.max_latency = max; + GST_OBJECT_UNLOCK (dec); +} + +/** + * gst_base_audio_decoder_get_latency: + * @dec: a #GstBaseAudioDecoder + * @min: a pointer to storage to hold minimum latency + * @max: a pointer to storage to hold maximum latency + * + * Returns currently configured latency. + * + * Since: 0.10.36 + */ +void +gst_base_audio_decoder_get_latency (GstBaseAudioDecoder * dec, + GstClockTime * min, GstClockTime * max) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec)); + + GST_OBJECT_LOCK (dec); + if (min) + *min = dec->priv->ctx.min_latency; + if (max) + *max = dec->priv->ctx.max_latency; + GST_OBJECT_UNLOCK (dec); +} + +/** + * gst_base_audio_decoder_get_parse_state: + * @dec: a #GstBaseAudioDecoder + * @min: a pointer to storage to hold current sync state + * @max: a pointer to storage to hold current eos state + * + * Return current parsing (sync and eos) state. + * + * Since: 0.10.36 + */ +void +gst_base_audio_decoder_get_parse_state (GstBaseAudioDecoder * dec, + gboolean * sync, gboolean * eos) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec)); + + if (sync) + *sync = dec->priv->ctx.sync; + if (eos) + *eos = dec->priv->ctx.eos; +} + +/** + * gst_base_audio_decoder_set_plc: + * @dec: a #GstBaseAudioDecoder + * @enabled: new state + * + * Enable or disable decoder packet loss concealment, provided subclass + * and codec are capable and allow handling plc. + * + * MT safe. + * + * Since: 0.10.36 + */ +void +gst_base_audio_decoder_set_plc (GstBaseAudioDecoder * dec, gboolean enabled) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec)); + + GST_LOG_OBJECT (dec, "enabled: %d", enabled); + + GST_OBJECT_LOCK (dec); + dec->priv->plc = enabled; + GST_OBJECT_UNLOCK (dec); +} + +/** + * gst_base_audio_decoder_get_plc: + * @dec: a #GstBaseAudioDecoder + * + * Queries decoder packet loss concealment handling. + * + * Returns: TRUE if packet loss concealment is enabled. + * + * MT safe. + * + * Since: 0.10.36 + */ +gboolean +gst_base_audio_decoder_get_plc (GstBaseAudioDecoder * dec) +{ + gboolean result; + + g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), FALSE); + + GST_OBJECT_LOCK (dec); + result = dec->priv->plc; + GST_OBJECT_UNLOCK (dec); + + return result; +} + +/** + * gst_base_audio_decoder_set_min_latency: + * @dec: a #GstBaseAudioDecoder + * @num: new minimum latency + * + * Sets decoder minimum aggregation latency. + * + * MT safe. + * + * Since: 0.10.36 + */ +void +gst_base_audio_decoder_set_min_latency (GstBaseAudioDecoder * dec, gint64 num) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec)); + + GST_OBJECT_LOCK (dec); + dec->priv->latency = num; + GST_OBJECT_UNLOCK (dec); +} + +/** + * gst_base_audio_decoder_get_min_latency: + * @enc: a #GstBaseAudioDecoder + * + * Queries decoder's latency aggregation. + * + * Returns: aggregation latency. + * + * MT safe. + * + * Since: 0.10.36 + */ +gint64 +gst_base_audio_decoder_get_min_latency (GstBaseAudioDecoder * dec) +{ + gint64 result; + + g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), FALSE); + + GST_OBJECT_LOCK (dec); + result = dec->priv->latency; + GST_OBJECT_UNLOCK (dec); + + return result; +} + +/** + * gst_base_audio_decoder_set_tolerance: + * @dec: a #GstBaseAudioDecoder + * @tolerance: new tolerance + * + * Configures decoder audio jitter tolerance threshold. + * + * MT safe. + * + * Since: 0.10.36 + */ +void +gst_base_audio_decoder_set_tolerance (GstBaseAudioDecoder * dec, + gint64 tolerance) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec)); + + GST_OBJECT_LOCK (dec); + dec->priv->tolerance = tolerance; + GST_OBJECT_UNLOCK (dec); +} + +/** + * gst_base_audio_decoder_get_tolerance: + * @dec: a #GstBaseAudioDecoder + * + * Queries current audio jitter tolerance threshold. + * + * Returns: decoder audio jitter tolerance threshold. + * + * MT safe. + * + * Since: 0.10.36 + */ +gint64 +gst_base_audio_decoder_get_tolerance (GstBaseAudioDecoder * dec) +{ + gint64 result; + + g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), 0); + + GST_OBJECT_LOCK (dec); + result = dec->priv->tolerance; + GST_OBJECT_UNLOCK (dec); + + return result; +} diff --git a/gst-libs/gst/audio/gstbaseaudiodecoder.h b/gst-libs/gst/audio/gstbaseaudiodecoder.h new file mode 100644 index 000000000..2f78779ff --- /dev/null +++ b/gst-libs/gst/audio/gstbaseaudiodecoder.h @@ -0,0 +1,275 @@ +/* GStreamer + * Copyright (C) 2009 Igalia S.L. + * Author: Iago Toral Quiroga <itoral@igalia.com> + * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>. + * Copyright (C) 2011 Nokia Corporation. All rights reserved. + * Contact: Stefan Kost <stefan.kost@nokia.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifndef _GST_BASE_AUDIO_DECODER_H_ +#define _GST_BASE_AUDIO_DECODER_H_ + +#ifndef GST_USE_UNSTABLE_API +#warning "GstBaseAudioDecoder is unstable API and may change in future." +#warning "You can define GST_USE_UNSTABLE_API to avoid this warning." +#endif + +#include <gst/gst.h> +#include <gst/audio/audio.h> +#include <gst/base/gstadapter.h> + +G_BEGIN_DECLS + +#define GST_TYPE_BASE_AUDIO_DECODER \ + (gst_base_audio_decoder_get_type()) +#define GST_BASE_AUDIO_DECODER(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_BASE_AUDIO_DECODER,GstBaseAudioDecoder)) +#define GST_BASE_AUDIO_DECODER_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_BASE_AUDIO_DECODER,GstBaseAudioDecoderClass)) +#define GST_BASE_AUDIO_DECODER_GET_CLASS(obj) \ + (G_TYPE_INSTANCE_GET_CLASS((obj),GST_TYPE_BASE_AUDIO_DECODER,GstBaseAudioDecoderClass)) +#define GST_IS_BASE_AUDIO_DECODER(obj) \ + (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_BASE_AUDIO_DECODER)) +#define GST_IS_BASE_AUDIO_DECODER_CLASS(obj) \ + (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_BASE_AUDIO_DECODER)) + +/** + * GST_BASE_AUDIO_DECODER_SINK_NAME: + * + * The name of the templates for the sink pad. + * + * Since: 0.10.36 + */ +#define GST_BASE_AUDIO_DECODER_SINK_NAME "sink" +/** + * GST_BASE_AUDIO_DECODER_SRC_NAME: + * + * The name of the templates for the source pad. + * + * Since: 0.10.36 + */ +#define GST_BASE_AUDIO_DECODER_SRC_NAME "src" + +/** + * GST_BASE_AUDIO_DECODER_SRC_PAD: + * @obj: base audio codec instance + * + * Gives the pointer to the source #GstPad object of the element. + * + * Since: 0.10.36 + */ +#define GST_BASE_AUDIO_DECODER_SRC_PAD(obj) (((GstBaseAudioDecoder *) (obj))->srcpad) + +/** + * GST_BASE_AUDIO_DECODER_SINK_PAD: + * @obj: base audio codec instance + * + * Gives the pointer to the sink #GstPad object of the element. + * + * Since: 0.10.36 + */ +#define GST_BASE_AUDIO_DECODER_SINK_PAD(obj) (((GstBaseAudioDecoder *) (obj))->sinkpad) + +typedef struct _GstBaseAudioDecoder GstBaseAudioDecoder; +typedef struct _GstBaseAudioDecoderClass GstBaseAudioDecoderClass; + +typedef struct _GstBaseAudioDecoderPrivate GstBaseAudioDecoderPrivate; + +/* do not use this one, use macro below */ +GstFlowReturn _gst_base_audio_decoder_error (GstBaseAudioDecoder *dec, gint weight, + GQuark domain, gint code, + gchar *txt, gchar *debug, + const gchar *file, const gchar *function, + gint line); + +/** + * GST_BASE_AUDIO_DECODER_ERROR: + * @el: the base audio decoder element that generates the error + * @weight: element defined weight of the error, added to error count + * @domain: like CORE, LIBRARY, RESOURCE or STREAM (see #gstreamer-GstGError) + * @code: error code defined for that domain (see #gstreamer-GstGError) + * @text: the message to display (format string and args enclosed in + * parentheses) + * @debug: debugging information for the message (format string and args + * enclosed in parentheses) + * @ret: variable to receive return value + * + * Utility function that audio decoder elements can use in case they encountered + * a data processing error that may be fatal for the current "data unit" but + * need not prevent subsequent decoding. Such errors are counted and if there + * are too many, as configured in the context's max_errors, the pipeline will + * post an error message and the application will be requested to stop further + * media processing. Otherwise, it is considered a "glitch" and only a warning + * is logged. In either case, @ret is set to the proper value to + * return to upstream/caller (indicating either GST_FLOW_ERROR or GST_FLOW_OK). + * + * Since: 0.10.36 + */ +#define GST_BASE_AUDIO_DECODER_ERROR(el, w, domain, code, text, debug, ret) \ +G_STMT_START { \ + gchar *__txt = _gst_element_error_printf text; \ + gchar *__dbg = _gst_element_error_printf debug; \ + GstBaseAudioDecoder *dec = GST_BASE_AUDIO_DECODER (el); \ + ret = _gst_base_audio_decoder_error (dec, w, GST_ ## domain ## _ERROR, \ + GST_ ## domain ## _ERROR_ ## code, __txt, __dbg, __FILE__, \ + GST_FUNCTION, __LINE__); \ +} G_STMT_END + +/** + * GstBaseAudioDecoder: + * + * The opaque #GstBaseAudioDecoder data structure. + * + * Since: 0.10.36 + */ +struct _GstBaseAudioDecoder +{ + GstElement element; + + /*< protected >*/ + /* source and sink pads */ + GstPad *sinkpad; + GstPad *srcpad; + + /* MT-protected (with STREAM_LOCK) */ + GstSegment segment; + + /*< private >*/ + GstBaseAudioDecoderPrivate *priv; + gpointer _gst_reserved[GST_PADDING_LARGE]; +}; + +/** + * GstBaseAudioDecoderClass: + * @start: Optional. + * Called when the element starts processing. + * Allows opening external resources. + * @stop: Optional. + * Called when the element stops processing. + * Allows closing external resources. + * @set_format: Notifies subclass of incoming data format (caps). + * @parse: Optional. + * Allows chopping incoming data into manageable units (frames) + * for subsequent decoding. This division is at subclass + * discretion and may or may not correspond to 1 (or more) + * frames as defined by audio format. + * @handle_frame: Provides input data (or NULL to clear any remaining data) + * to subclass. Input data ref management is performed by + * base class, subclass should not care or intervene. + * @flush: Optional. + * Instructs subclass to clear any codec caches and discard + * any pending samples and not yet returned encoded data. + * @hard indicates whether a FLUSH is being processed, + * or otherwise a DISCONT (or conceptually similar). + * @event: Optional. + * Event handler on the sink pad. This function should return + * TRUE if the event was handled and should be discarded + * (i.e. not unref'ed). + * @pre_push: Optional. + * Called just prior to pushing (encoded data) buffer downstream. + * Subclass has full discretionary access to buffer, + * and a not OK flow return will abort downstream pushing. + * + * Subclasses can override any of the available virtual methods or not, as + * needed. At minimum @handle_frame (and likely @set_format) needs to be + * overridden. + * + * Since: 0.10.36 + */ +struct _GstBaseAudioDecoderClass +{ + GstElementClass parent_class; + + /*< public >*/ + /* virtual methods for subclasses */ + + gboolean (*start) (GstBaseAudioDecoder *dec); + + gboolean (*stop) (GstBaseAudioDecoder *dec); + + gboolean (*set_format) (GstBaseAudioDecoder *dec, + GstCaps *caps); + + GstFlowReturn (*parse) (GstBaseAudioDecoder *dec, + GstAdapter *adapter, + gint *offset, gint *length); + + GstFlowReturn (*handle_frame) (GstBaseAudioDecoder *dec, + GstBuffer *buffer); + + void (*flush) (GstBaseAudioDecoder *dec, gboolean hard); + + GstFlowReturn (*pre_push) (GstBaseAudioDecoder *dec, + GstBuffer **buffer); + + gboolean (*event) (GstBaseAudioDecoder *dec, + GstEvent *event); + + /*< private >*/ + gpointer _gst_reserved[GST_PADDING_LARGE]; +}; + +GstFlowReturn gst_base_audio_decoder_finish_frame (GstBaseAudioDecoder * dec, + GstBuffer * buf, gint frames); + +/* context parameters */ +GstAudioInfo * gst_base_audio_decoder_get_audio_info (GstBaseAudioDecoder * dec); + +void gst_base_audio_decoder_set_plc_aware (GstBaseAudioDecoder * dec, + gboolean plc); +gint gst_base_audio_decoder_get_plc_aware (GstBaseAudioDecoder * dec); + +void gst_base_audio_decoder_set_byte_time (GstBaseAudioDecoder * dec, + gboolean enabled); +gint gst_base_audio_decoder_get_byte_time (GstBaseAudioDecoder * dec); + +gint gst_base_audio_decoder_get_delay (GstBaseAudioDecoder * dec); + +void gst_base_audio_decoder_set_max_errors (GstBaseAudioDecoder * enc, + gint num); +gint gst_base_audio_decoder_get_max_errors (GstBaseAudioDecoder * dec); + +void gst_base_audio_decoder_set_latency (GstBaseAudioDecoder * dec, + GstClockTime min, GstClockTime max); +void gst_base_audio_decoder_get_latency (GstBaseAudioDecoder * dec, + GstClockTime * min, GstClockTime * max); + +void gst_base_audio_decoder_get_parse_state (GstBaseAudioDecoder * dec, + gboolean * sync, gboolean * eos); + + +/* object properties */ +void gst_base_audio_decoder_set_plc (GstBaseAudioDecoder * dec, + gboolean enabled); +gboolean gst_base_audio_decoder_get_plc (GstBaseAudioDecoder * dec); + +void gst_base_audio_decoder_set_min_latency (GstBaseAudioDecoder * dec, + gint64 num); +gint64 gst_base_audio_decoder_get_min_latency (GstBaseAudioDecoder * dec); + +void gst_base_audio_decoder_set_tolerance (GstBaseAudioDecoder * dec, + gint64 tolerance); + +gint64 gst_base_audio_decoder_get_tolerance (GstBaseAudioDecoder * dec); + +GType gst_base_audio_decoder_get_type (void); + +G_END_DECLS + +#endif + diff --git a/gst-libs/gst/audio/gstbaseaudioencoder.c b/gst-libs/gst/audio/gstbaseaudioencoder.c new file mode 100644 index 000000000..63131fd10 --- /dev/null +++ b/gst-libs/gst/audio/gstbaseaudioencoder.c @@ -0,0 +1,1935 @@ +/* GStreamer + * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>. + * Copyright (C) 2011 Nokia Corporation. All rights reserved. + * Contact: Stefan Kost <stefan.kost@nokia.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +/** + * SECTION:gstbaseaudioencoder + * @short_description: Base class for audio encoders + * @see_also: #GstBaseTransform + * @since: 0.10.36 + * + * This base class is for audio encoders turning raw audio samples into + * encoded audio data. + * + * GstBaseAudioEncoder and subclass should cooperate as follows. + * <orderedlist> + * <listitem> + * <itemizedlist><title>Configuration</title> + * <listitem><para> + * Initially, GstBaseAudioEncoder calls @start when the encoder element + * is activated, which allows subclass to perform any global setup. + * </para></listitem> + * <listitem><para> + * GstBaseAudioEncoder calls @set_format to inform subclass of the format + * of input audio data that it is about to receive. Subclass should + * setup for encoding and configure various base class parameters + * appropriately, notably those directing desired input data handling. + * While unlikely, it might be called more than once, if changing input + * parameters require reconfiguration. + * </para></listitem> + * <listitem><para> + * GstBaseAudioEncoder calls @stop at end of all processing. + * </para></listitem> + * </itemizedlist> + * </listitem> + * As of configuration stage, and throughout processing, GstBaseAudioEncoder + * maintains various parameters that provide required context, + * e.g. describing the format of input audio data. + * Conversely, subclass can and should configure these context parameters + * to inform base class of its expectation w.r.t. buffer handling. + * <listitem> + * <itemizedlist> + * <title>Data processing</title> + * <listitem><para> + * Base class gathers input sample data (as directed by the context's + * frame_samples and frame_max) and provides this to subclass' @handle_frame. + * </para></listitem> + * <listitem><para> + * If codec processing results in encoded data, subclass should call + * @gst_base_audio_encoder_finish_frame to have encoded data pushed + * downstream. Alternatively, it might also call to indicate dropped + * (non-encoded) samples. + * </para></listitem> + * <listitem><para> + * Just prior to actually pushing a buffer downstream, + * it is passed to @pre_push. + * </para></listitem> + * <listitem><para> + * During the parsing process GstBaseAudioEncoderClass will handle both + * srcpad and sinkpad events. Sink events will be passed to subclass + * if @event callback has been provided. + * </para></listitem> + * </itemizedlist> + * </listitem> + * <listitem> + * <itemizedlist><title>Shutdown phase</title> + * <listitem><para> + * GstBaseAudioEncoder class calls @stop to inform the subclass that data + * parsing will be stopped. + * </para></listitem> + * </itemizedlist> + * </listitem> + * </orderedlist> + * + * Subclass is responsible for providing pad template caps for + * source and sink pads. The pads need to be named "sink" and "src". It also + * needs to set the fixed caps on srcpad, when the format is ensured. This + * is typically when base class calls subclass' @set_format function, though + * it might be delayed until calling @gst_base_audio_encoder_finish_frame. + * + * In summary, above process should have subclass concentrating on + * codec data processing while leaving other matters to base class, + * such as most notably timestamp handling. While it may exert more control + * in this area (see e.g. @pre_push), it is very much not recommended. + * + * In particular, base class will either favor tracking upstream timestamps + * (at the possible expense of jitter) or aim to arrange for a perfect stream of + * output timestamps, depending on #GstBaseAudioEncoder:perfect-ts. + * However, in the latter case, the input may not be so perfect or ideal, which + * is handled as follows. An input timestamp is compared with the expected + * timestamp as dictated by input sample stream and if the deviation is less + * than #GstBaseAudioEncoder:tolerance, the deviation is discarded. + * Otherwise, it is considered a discontuinity and subsequent output timestamp + * is resynced to the new position after performing configured discontinuity + * processing. In the non-perfect-ts case, an upstream variation exceeding + * tolerance only leads to marking DISCONT on subsequent outgoing + * (while timestamps are adjusted to upstream regardless of variation). + * While DISCONT is also marked in the perfect-ts case, this one optionally + * (see #GstBaseAudioEncoder:hard-resync) + * performs some additional steps, such as clipping of (early) input samples + * or draining all currently remaining input data, depending on the direction + * of the discontuinity. + * + * If perfect timestamps are arranged, it is also possible to request baseclass + * (usually set by subclass) to provide additional buffer metadata (in OFFSET + * and OFFSET_END) fields according to granule defined semantics currently + * needed by oggmux. Specifically, OFFSET is set to granulepos (= sample count + * including buffer) and OFFSET_END to corresponding timestamp (as determined + * by same sample count and sample rate). + * + * Things that subclass need to take care of: + * <itemizedlist> + * <listitem><para>Provide pad templates</para></listitem> + * <listitem><para> + * Set source pad caps when appropriate + * </para></listitem> + * <listitem><para> + * Inform base class of buffer processing needs using context's + * frame_samples and frame_bytes. + * </para></listitem> + * <listitem><para> + * Set user-configurable properties to sane defaults for format and + * implementing codec at hand, e.g. those controlling timestamp behaviour + * and discontinuity processing. + * </para></listitem> + * <listitem><para> + * Accept data in @handle_frame and provide encoded results to + * @gst_base_audio_encoder_finish_frame. + * </para></listitem> + * </itemizedlist> + * + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#define GST_USE_UNSTABLE_API +#include "gstbaseaudioencoder.h" +#include <gst/base/gstadapter.h> +#include <gst/audio/audio.h> + +#include <stdlib.h> +#include <string.h> + + +GST_DEBUG_CATEGORY_STATIC (gst_base_audio_encoder_debug); +#define GST_CAT_DEFAULT gst_base_audio_encoder_debug + +#define GST_BASE_AUDIO_ENCODER_GET_PRIVATE(obj) \ + (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_AUDIO_ENCODER, \ + GstBaseAudioEncoderPrivate)) + +enum +{ + PROP_0, + PROP_PERFECT_TS, + PROP_GRANULE, + PROP_HARD_RESYNC, + PROP_TOLERANCE +}; + +#define DEFAULT_PERFECT_TS FALSE +#define DEFAULT_GRANULE FALSE +#define DEFAULT_HARD_RESYNC FALSE +#define DEFAULT_TOLERANCE 40000000 + +typedef struct _GstBaseAudioEncoderContext +{ + /* input */ + GstAudioInfo info; + + /* output */ + gint frame_samples; + gint frame_max; + gint lookahead; + /* MT-protected (with LOCK) */ + GstClockTime min_latency; + GstClockTime max_latency; +} GstBaseAudioEncoderContext; + +struct _GstBaseAudioEncoderPrivate +{ + /* activation status */ + gboolean active; + + /* input base/first ts as basis for output ts; + * kept nearly constant for perfect_ts, + * otherwise resyncs to upstream ts */ + GstClockTime base_ts; + /* corresponding base granulepos */ + gint64 base_gp; + /* input samples processed and sent downstream so far (w.r.t. base_ts) */ + guint64 samples; + + /* currently collected sample data */ + GstAdapter *adapter; + /* offset in adapter up to which already supplied to encoder */ + gint offset; + /* mark outgoing discont */ + gboolean discont; + /* to guess duration of drained data */ + GstClockTime last_duration; + + /* subclass provided data in processing round */ + gboolean got_data; + /* subclass gave all it could already */ + gboolean drained; + /* subclass currently being forcibly drained */ + gboolean force; + + /* output bps estimatation */ + /* global in samples seen */ + guint64 samples_in; + /* global bytes sent out */ + guint64 bytes_out; + + /* context storage */ + GstBaseAudioEncoderContext ctx; + + /* properties */ + gint64 tolerance; + gboolean perfect_ts; + gboolean hard_resync; + gboolean granule; +}; + + +static GstElementClass *parent_class = NULL; + +static void gst_base_audio_encoder_class_init (GstBaseAudioEncoderClass * + klass); +static void gst_base_audio_encoder_init (GstBaseAudioEncoder * parse, + GstBaseAudioEncoderClass * klass); + +GType +gst_base_audio_encoder_get_type (void) +{ + static GType base_audio_encoder_type = 0; + + if (!base_audio_encoder_type) { + static const GTypeInfo base_audio_encoder_info = { + sizeof (GstBaseAudioEncoderClass), + (GBaseInitFunc) NULL, + (GBaseFinalizeFunc) NULL, + (GClassInitFunc) gst_base_audio_encoder_class_init, + NULL, + NULL, + sizeof (GstBaseAudioEncoder), + 0, + (GInstanceInitFunc) gst_base_audio_encoder_init, + }; + const GInterfaceInfo preset_interface_info = { + NULL, /* interface_init */ + NULL, /* interface_finalize */ + NULL /* interface_data */ + }; + + base_audio_encoder_type = g_type_register_static (GST_TYPE_ELEMENT, + "GstBaseAudioEncoder", &base_audio_encoder_info, G_TYPE_FLAG_ABSTRACT); + + g_type_add_interface_static (base_audio_encoder_type, GST_TYPE_PRESET, + &preset_interface_info); + } + return base_audio_encoder_type; +} + +static void gst_base_audio_encoder_finalize (GObject * object); +static void gst_base_audio_encoder_reset (GstBaseAudioEncoder * enc, + gboolean full); + +static void gst_base_audio_encoder_set_property (GObject * object, + guint prop_id, const GValue * value, GParamSpec * pspec); +static void gst_base_audio_encoder_get_property (GObject * object, + guint prop_id, GValue * value, GParamSpec * pspec); + +static gboolean gst_base_audio_encoder_sink_activate_push (GstPad * pad, + gboolean active); + +static gboolean gst_base_audio_encoder_sink_event (GstPad * pad, + GstEvent * event); +static gboolean gst_base_audio_encoder_sink_setcaps (GstPad * pad, + GstCaps * caps); +static GstFlowReturn gst_base_audio_encoder_chain (GstPad * pad, + GstBuffer * buffer); +static gboolean gst_base_audio_encoder_src_query (GstPad * pad, + GstQuery * query); +static gboolean gst_base_audio_encoder_sink_query (GstPad * pad, + GstQuery * query); +static const GstQueryType *gst_base_audio_encoder_get_query_types (GstPad * + pad); +static GstCaps *gst_base_audio_encoder_sink_getcaps (GstPad * pad); + + +static void +gst_base_audio_encoder_class_init (GstBaseAudioEncoderClass * klass) +{ + GObjectClass *gobject_class; + + gobject_class = G_OBJECT_CLASS (klass); + parent_class = g_type_class_peek_parent (klass); + + GST_DEBUG_CATEGORY_INIT (gst_base_audio_encoder_debug, "baseaudioencoder", 0, + "baseaudioencoder element"); + + g_type_class_add_private (klass, sizeof (GstBaseAudioEncoderPrivate)); + + gobject_class->set_property = gst_base_audio_encoder_set_property; + gobject_class->get_property = gst_base_audio_encoder_get_property; + + gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_audio_encoder_finalize); + + /* properties */ + g_object_class_install_property (gobject_class, PROP_PERFECT_TS, + g_param_spec_boolean ("perfect-timestamp", "Perfect Timestamps", + "Favour perfect timestamps over tracking upstream timestamps", + DEFAULT_PERFECT_TS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + g_object_class_install_property (gobject_class, PROP_GRANULE, + g_param_spec_boolean ("mark-granule", "Granule Marking", + "Apply granule semantics to buffer metadata (implies perfect-ts)", + DEFAULT_GRANULE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + g_object_class_install_property (gobject_class, PROP_HARD_RESYNC, + g_param_spec_boolean ("hard-resync", "Hard Resync", + "Perform clipping and sample flushing upon discontinuity", + DEFAULT_HARD_RESYNC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + g_object_class_install_property (gobject_class, PROP_TOLERANCE, + g_param_spec_int64 ("tolerance", "Tolerance", + "Consider discontinuity if timestamp jitter/imperfection exceeds tolerance (ns)", + 0, G_MAXINT64, DEFAULT_TOLERANCE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gst_base_audio_encoder_init (GstBaseAudioEncoder * enc, + GstBaseAudioEncoderClass * bclass) +{ + GstPadTemplate *pad_template; + + GST_DEBUG_OBJECT (enc, "gst_base_audio_encoder_init"); + + enc->priv = GST_BASE_AUDIO_ENCODER_GET_PRIVATE (enc); + + /* only push mode supported */ + pad_template = + gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink"); + g_return_if_fail (pad_template != NULL); + enc->sinkpad = gst_pad_new_from_template (pad_template, "sink"); + gst_pad_set_event_function (enc->sinkpad, + GST_DEBUG_FUNCPTR (gst_base_audio_encoder_sink_event)); + gst_pad_set_setcaps_function (enc->sinkpad, + GST_DEBUG_FUNCPTR (gst_base_audio_encoder_sink_setcaps)); + gst_pad_set_getcaps_function (enc->sinkpad, + GST_DEBUG_FUNCPTR (gst_base_audio_encoder_sink_getcaps)); + gst_pad_set_query_function (enc->sinkpad, + GST_DEBUG_FUNCPTR (gst_base_audio_encoder_sink_query)); + gst_pad_set_chain_function (enc->sinkpad, + GST_DEBUG_FUNCPTR (gst_base_audio_encoder_chain)); + gst_pad_set_activatepush_function (enc->sinkpad, + GST_DEBUG_FUNCPTR (gst_base_audio_encoder_sink_activate_push)); + gst_element_add_pad (GST_ELEMENT (enc), enc->sinkpad); + + GST_DEBUG_OBJECT (enc, "sinkpad created"); + + /* and we don't mind upstream traveling stuff that much ... */ + pad_template = + gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src"); + g_return_if_fail (pad_template != NULL); + enc->srcpad = gst_pad_new_from_template (pad_template, "src"); + gst_pad_set_query_function (enc->srcpad, + GST_DEBUG_FUNCPTR (gst_base_audio_encoder_src_query)); + gst_pad_set_query_type_function (enc->srcpad, + GST_DEBUG_FUNCPTR (gst_base_audio_encoder_get_query_types)); + gst_pad_use_fixed_caps (enc->srcpad); + gst_element_add_pad (GST_ELEMENT (enc), enc->srcpad); + GST_DEBUG_OBJECT (enc, "src created"); + + enc->priv->adapter = gst_adapter_new (); + + /* property default */ + enc->priv->granule = DEFAULT_GRANULE; + enc->priv->perfect_ts = DEFAULT_PERFECT_TS; + enc->priv->hard_resync = DEFAULT_HARD_RESYNC; + enc->priv->tolerance = DEFAULT_TOLERANCE; + + /* init state */ + gst_base_audio_encoder_reset (enc, TRUE); + GST_DEBUG_OBJECT (enc, "init ok"); +} + +static void +gst_base_audio_encoder_reset (GstBaseAudioEncoder * enc, gboolean full) +{ + GST_OBJECT_LOCK (enc); + + if (full) { + enc->priv->active = FALSE; + enc->priv->samples_in = 0; + enc->priv->bytes_out = 0; + gst_audio_info_clear (&enc->priv->ctx.info); + memset (&enc->priv->ctx, 0, sizeof (enc->priv->ctx)); + } + + gst_segment_init (&enc->segment, GST_FORMAT_TIME); + + gst_adapter_clear (enc->priv->adapter); + enc->priv->got_data = FALSE; + enc->priv->drained = TRUE; + enc->priv->offset = 0; + enc->priv->base_ts = GST_CLOCK_TIME_NONE; + enc->priv->base_gp = -1; + enc->priv->samples = 0; + enc->priv->discont = FALSE; + + GST_OBJECT_UNLOCK (enc); +} + +static void +gst_base_audio_encoder_finalize (GObject * object) +{ + GstBaseAudioEncoder *enc = GST_BASE_AUDIO_ENCODER (object); + + g_object_unref (enc->priv->adapter); + + G_OBJECT_CLASS (parent_class)->finalize (object); +} + +/** + * gst_base_audio_encoder_finish_frame: + * @enc: a #GstBaseAudioEncoder + * @buffer: encoded data + * @samples: number of samples (per channel) represented by encoded data + * + * Collects encoded data and/or pushes encoded data downstream. + * Source pad caps must be set when this is called. Depending on the nature + * of the (framing of) the format, subclass can decide whether to push + * encoded data directly or to collect various "frames" in a single buffer. + * Note that the latter behaviour is recommended whenever the format is allowed, + * as it incurs no additional latency and avoids otherwise generating a + * a multitude of (small) output buffers. If not explicitly pushed, + * any available encoded data is pushed at the end of each processing cycle, + * i.e. which encodes as much data as available input data allows. + * + * If @samples < 0, then best estimate is all samples provided to encoder + * (subclass) so far. @buf may be NULL, in which case next number of @samples + * are considered discarded, e.g. as a result of discontinuous transmission, + * and a discontinuity is marked (note that @buf == NULL => push == TRUE). + * + * Returns: a #GstFlowReturn that should be escalated to caller (of caller) + * + * Since: 0.10.36 + */ +GstFlowReturn +gst_base_audio_encoder_finish_frame (GstBaseAudioEncoder * enc, GstBuffer * buf, + gint samples) +{ + GstBaseAudioEncoderClass *klass; + GstBaseAudioEncoderPrivate *priv; + GstBaseAudioEncoderContext *ctx; + GstFlowReturn ret = GST_FLOW_OK; + + klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc); + priv = enc->priv; + ctx = &enc->priv->ctx; + + /* subclass should know what it is producing by now */ + g_return_val_if_fail (GST_PAD_CAPS (enc->srcpad) != NULL, GST_FLOW_ERROR); + /* subclass should not hand us no data */ + g_return_val_if_fail (buf == NULL || GST_BUFFER_SIZE (buf) > 0, + GST_FLOW_ERROR); + + GST_LOG_OBJECT (enc, "accepting %d bytes encoded data as %d samples", + buf ? GST_BUFFER_SIZE (buf) : -1, samples); + + /* mark subclass still alive and providing */ + priv->got_data = TRUE; + + /* remove corresponding samples from input */ + if (samples < 0) + samples = (enc->priv->offset / ctx->info.bpf); + + if (G_LIKELY (samples)) { + /* track upstream ts if so configured */ + if (!enc->priv->perfect_ts) { + guint64 ts, distance; + + ts = gst_adapter_prev_timestamp (priv->adapter, &distance); + g_assert (distance % ctx->info.bpf == 0); + distance /= ctx->info.bpf; + GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past prev_ts %" + GST_TIME_FORMAT, distance, GST_TIME_ARGS (ts)); + GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past base_ts %" + GST_TIME_FORMAT, priv->samples, GST_TIME_ARGS (priv->base_ts)); + /* when draining adapter might be empty and no ts to offer */ + if (GST_CLOCK_TIME_IS_VALID (ts) && ts != priv->base_ts) { + GstClockTimeDiff diff; + GstClockTime old_ts, next_ts; + + /* passed into another buffer; + * mild check for discontinuity and only mark if so */ + next_ts = ts + + gst_util_uint64_scale (distance, GST_SECOND, ctx->info.rate); + old_ts = priv->base_ts + + gst_util_uint64_scale (priv->samples, GST_SECOND, ctx->info.rate); + diff = GST_CLOCK_DIFF (next_ts, old_ts); + GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND)); + /* only mark discontinuity if beyond tolerance */ + if (G_UNLIKELY (diff < -enc->priv->tolerance || + diff > enc->priv->tolerance)) { + GST_DEBUG_OBJECT (enc, "marked discont"); + priv->discont = TRUE; + } + if (diff > GST_SECOND / ctx->info.rate / 2 || + diff < -GST_SECOND / ctx->info.rate / 2) { + GST_LOG_OBJECT (enc, "new upstream ts %" GST_TIME_FORMAT + " at distance %" G_GUINT64_FORMAT, GST_TIME_ARGS (ts), distance); + /* re-sync to upstream ts */ + priv->base_ts = ts; + priv->samples = distance; + } else { + GST_LOG_OBJECT (enc, "new upstream ts only introduces jitter"); + } + } + } + /* advance sample view */ + if (G_UNLIKELY (samples * ctx->info.bpf > priv->offset)) { + if (G_LIKELY (!priv->force)) { + /* no way we can let this pass */ + g_assert_not_reached (); + /* really no way */ + goto overflow; + } else { + priv->offset = 0; + if (samples * ctx->info.bpf >= gst_adapter_available (priv->adapter)) + gst_adapter_clear (priv->adapter); + else + gst_adapter_flush (priv->adapter, samples * ctx->info.bpf); + } + } else { + gst_adapter_flush (priv->adapter, samples * ctx->info.bpf); + priv->offset -= samples * ctx->info.bpf; + /* avoid subsequent stray prev_ts */ + if (G_UNLIKELY (gst_adapter_available (priv->adapter) == 0)) + gst_adapter_clear (priv->adapter); + } + /* sample count advanced below after buffer handling */ + } + + /* collect output */ + if (G_LIKELY (buf)) { + GST_LOG_OBJECT (enc, "taking %d bytes for output", GST_BUFFER_SIZE (buf)); + buf = gst_buffer_make_metadata_writable (buf); + + /* decorate */ + gst_buffer_set_caps (buf, GST_PAD_CAPS (enc->srcpad)); + if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (priv->base_ts))) { + /* FIXME ? lookahead could lead to weird ts and duration ? + * (particularly if not in perfect mode) */ + /* mind sample rounding and produce perfect output */ + GST_BUFFER_TIMESTAMP (buf) = priv->base_ts + + gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND, + ctx->info.rate); + GST_DEBUG_OBJECT (enc, "out samples %d", samples); + if (G_LIKELY (samples > 0)) { + priv->samples += samples; + GST_BUFFER_DURATION (buf) = priv->base_ts + + gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND, + ctx->info.rate) - GST_BUFFER_TIMESTAMP (buf); + priv->last_duration = GST_BUFFER_DURATION (buf); + } else { + /* duration forecast in case of handling remainder; + * the last one is probably like the previous one ... */ + GST_BUFFER_DURATION (buf) = priv->last_duration; + } + if (priv->base_gp >= 0) { + /* pamper oggmux */ + /* FIXME: in longer run, muxer should take care of this ... */ + /* offset_end = granulepos for ogg muxer */ + GST_BUFFER_OFFSET_END (buf) = priv->base_gp + priv->samples - + enc->priv->ctx.lookahead; + /* offset = timestamp corresponding to granulepos for ogg muxer */ + GST_BUFFER_OFFSET (buf) = + GST_FRAMES_TO_CLOCK_TIME (GST_BUFFER_OFFSET_END (buf), + ctx->info.rate); + } else { + GST_BUFFER_OFFSET (buf) = priv->bytes_out; + GST_BUFFER_OFFSET_END (buf) = priv->bytes_out + GST_BUFFER_SIZE (buf); + } + } + + priv->bytes_out += GST_BUFFER_SIZE (buf); + + if (G_UNLIKELY (priv->discont)) { + GST_LOG_OBJECT (enc, "marking discont"); + GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT); + priv->discont = FALSE; + } + + if (klass->pre_push) { + /* last chance for subclass to do some dirty stuff */ + ret = klass->pre_push (enc, &buf); + if (ret != GST_FLOW_OK || !buf) { + GST_DEBUG_OBJECT (enc, "subclass returned %s, buf %p", + gst_flow_get_name (ret), buf); + if (buf) + gst_buffer_unref (buf); + goto exit; + } + } + + GST_LOG_OBJECT (enc, "pushing buffer of size %d with ts %" GST_TIME_FORMAT + ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buf), + GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)), + GST_TIME_ARGS (GST_BUFFER_DURATION (buf))); + + ret = gst_pad_push (enc->srcpad, buf); + GST_LOG_OBJECT (enc, "buffer pushed: %s", gst_flow_get_name (ret)); + } else { + /* merely advance samples, most work for that already done above */ + priv->samples += samples; + } + +exit: + return ret; + + /* ERRORS */ +overflow: + { + GST_ELEMENT_ERROR (enc, STREAM, ENCODE, + ("received more encoded samples %d than provided %d", + samples, priv->offset / ctx->info.bpf), (NULL)); + if (buf) + gst_buffer_unref (buf); + return GST_FLOW_ERROR; + } +} + + /* adapter tracking idea: + * - start of adapter corresponds with what has already been encoded + * (i.e. really returned by encoder subclass) + * - start + offset is what needs to be fed to subclass next */ +static GstFlowReturn +gst_base_audio_encoder_push_buffers (GstBaseAudioEncoder * enc, gboolean force) +{ + GstBaseAudioEncoderClass *klass; + GstBaseAudioEncoderPrivate *priv; + GstBaseAudioEncoderContext *ctx; + gint av, need; + GstBuffer *buf; + GstFlowReturn ret = GST_FLOW_OK; + + klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc); + + g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR); + + priv = enc->priv; + ctx = &enc->priv->ctx; + + while (ret == GST_FLOW_OK) { + + buf = NULL; + av = gst_adapter_available (priv->adapter); + + g_assert (priv->offset <= av); + av -= priv->offset; + + need = ctx->frame_samples > 0 ? ctx->frame_samples * ctx->info.bpf : av; + GST_LOG_OBJECT (enc, "available: %d, needed: %d, force: %d", + av, need, force); + + if ((need > av) || !av) { + if (G_UNLIKELY (force)) { + priv->force = TRUE; + need = av; + } else { + break; + } + } else { + priv->force = FALSE; + } + + /* if we have some extra metadata, + * provide for integer multiple of frames to allow for better granularity + * of processing */ + if (ctx->frame_samples > 0 && need) { + if (ctx->frame_max > 1) + need = need * MIN ((av / need), ctx->frame_max); + else if (ctx->frame_max == 0) + need = need * (av / need); + } + + if (need) { + buf = gst_buffer_new (); + GST_BUFFER_DATA (buf) = (guint8 *) + gst_adapter_peek (priv->adapter, priv->offset + need) + priv->offset; + GST_BUFFER_SIZE (buf) = need; + } + + GST_LOG_OBJECT (enc, "providing subclass with %d bytes at offset %d", + need, priv->offset); + + /* mark this already as consumed, + * which it should be when subclass gives us data in exchange for samples */ + priv->offset += need; + priv->samples_in += need / ctx->info.bpf; + + priv->got_data = FALSE; + ret = klass->handle_frame (enc, buf); + + if (G_LIKELY (buf)) + gst_buffer_unref (buf); + + /* no data to feed, no leftover provided, then bail out */ + if (G_UNLIKELY (!buf && !priv->got_data)) { + priv->drained = TRUE; + GST_LOG_OBJECT (enc, "no more data drained from subclass"); + break; + } + } + + return ret; +} + +static GstFlowReturn +gst_base_audio_encoder_drain (GstBaseAudioEncoder * enc) +{ + if (enc->priv->drained) + return GST_FLOW_OK; + else + return gst_base_audio_encoder_push_buffers (enc, TRUE); +} + +static void +gst_base_audio_encoder_set_base_gp (GstBaseAudioEncoder * enc) +{ + GstClockTime ts; + + if (!enc->priv->granule) + return; + + /* use running time for granule */ + /* incoming data is clipped, so a valid input should yield a valid output */ + ts = gst_segment_to_running_time (&enc->segment, GST_FORMAT_TIME, + enc->priv->base_ts); + if (GST_CLOCK_TIME_IS_VALID (ts)) { + enc->priv->base_gp = + GST_CLOCK_TIME_TO_FRAMES (enc->priv->base_ts, enc->priv->ctx.info.rate); + GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT, enc->priv->base_gp); + } else { + /* should reasonably have a valid base, + * otherwise start at 0 if we did not already start there earlier */ + if (enc->priv->base_gp < 0) { + enc->priv->base_gp = 0; + GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT, + enc->priv->base_gp); + } + } +} + +static GstFlowReturn +gst_base_audio_encoder_chain (GstPad * pad, GstBuffer * buffer) +{ + GstBaseAudioEncoder *enc; + GstBaseAudioEncoderPrivate *priv; + GstBaseAudioEncoderContext *ctx; + GstFlowReturn ret = GST_FLOW_OK; + gboolean discont; + + enc = GST_BASE_AUDIO_ENCODER (GST_OBJECT_PARENT (pad)); + + priv = enc->priv; + ctx = &enc->priv->ctx; + + /* should know what is coming by now */ + if (!ctx->info.bpf) + goto not_negotiated; + + GST_LOG_OBJECT (enc, + "received buffer of size %d with ts %" GST_TIME_FORMAT + ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer), + GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)), + GST_TIME_ARGS (GST_BUFFER_DURATION (buffer))); + + /* input shoud be whole number of sample frames */ + if (GST_BUFFER_SIZE (buffer) % ctx->info.bpf) + goto wrong_buffer; + +#ifndef GST_DISABLE_GST_DEBUG + { + GstClockTime duration; + GstClockTimeDiff diff; + + /* verify buffer duration */ + duration = gst_util_uint64_scale (GST_BUFFER_SIZE (buffer), GST_SECOND, + ctx->info.rate * ctx->info.bpf); + diff = GST_CLOCK_DIFF (duration, GST_BUFFER_DURATION (buffer)); + if (GST_BUFFER_DURATION (buffer) != GST_CLOCK_TIME_NONE && + (diff > GST_SECOND / ctx->info.rate / 2 || + diff < -GST_SECOND / ctx->info.rate / 2)) { + GST_DEBUG_OBJECT (enc, "incoming buffer had incorrect duration %" + GST_TIME_FORMAT ", expected duration %" GST_TIME_FORMAT, + GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)), + GST_TIME_ARGS (duration)); + } + } +#endif + + discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT); + if (G_UNLIKELY (discont)) { + GST_LOG_OBJECT (buffer, "marked discont"); + enc->priv->discont = discont; + } + + /* clip to segment */ + /* NOTE: slightly painful linking -laudio only for this one ... */ + buffer = gst_audio_buffer_clip (buffer, &enc->segment, ctx->info.rate, + ctx->info.bpf); + if (G_UNLIKELY (!buffer)) { + GST_DEBUG_OBJECT (buffer, "no data after clipping to segment"); + goto done; + } + + GST_LOG_OBJECT (enc, + "buffer after segment clipping has size %d with ts %" GST_TIME_FORMAT + ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer), + GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)), + GST_TIME_ARGS (GST_BUFFER_DURATION (buffer))); + + if (!GST_CLOCK_TIME_IS_VALID (priv->base_ts)) { + priv->base_ts = GST_BUFFER_TIMESTAMP (buffer); + GST_DEBUG_OBJECT (enc, "new base ts %" GST_TIME_FORMAT, + GST_TIME_ARGS (priv->base_ts)); + gst_base_audio_encoder_set_base_gp (enc); + } + + /* check for continuity; + * checked elsewhere in non-perfect case */ + if (enc->priv->perfect_ts) { + GstClockTimeDiff diff = 0; + GstClockTime next_ts = 0; + + if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && + GST_CLOCK_TIME_IS_VALID (priv->base_ts)) { + guint64 samples; + + samples = priv->samples + + gst_adapter_available (priv->adapter) / ctx->info.bpf; + next_ts = priv->base_ts + + gst_util_uint64_scale (samples, GST_SECOND, ctx->info.rate); + GST_LOG_OBJECT (enc, "buffer is %" G_GUINT64_FORMAT + " samples past base_ts %" GST_TIME_FORMAT + ", expected ts %" GST_TIME_FORMAT, samples, + GST_TIME_ARGS (priv->base_ts), GST_TIME_ARGS (next_ts)); + diff = GST_CLOCK_DIFF (next_ts, GST_BUFFER_TIMESTAMP (buffer)); + GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND)); + /* if within tolerance, + * discard buffer ts and carry on producing perfect stream, + * otherwise clip or resync to ts */ + if (G_UNLIKELY (diff < -enc->priv->tolerance || + diff > enc->priv->tolerance)) { + GST_DEBUG_OBJECT (enc, "marked discont"); + discont = TRUE; + } + } + + /* do some fancy tweaking in hard resync case */ + if (discont && enc->priv->hard_resync) { + if (diff < 0) { + guint64 diff_bytes; + + GST_WARNING_OBJECT (enc, "Buffer is older than expected ts %" + GST_TIME_FORMAT ". Clipping buffer", GST_TIME_ARGS (next_ts)); + + diff_bytes = + GST_CLOCK_TIME_TO_FRAMES (-diff, ctx->info.rate) * ctx->info.bpf; + if (diff_bytes >= GST_BUFFER_SIZE (buffer)) { + gst_buffer_unref (buffer); + goto done; + } + buffer = gst_buffer_make_metadata_writable (buffer); + GST_BUFFER_DATA (buffer) += diff_bytes; + GST_BUFFER_SIZE (buffer) -= diff_bytes; + + GST_BUFFER_TIMESTAMP (buffer) += diff; + /* care even less about duration after this */ + } else { + /* drain stuff prior to resync */ + gst_base_audio_encoder_drain (enc); + } + } + /* now re-sync ts */ + priv->base_ts += diff; + gst_base_audio_encoder_set_base_gp (enc); + priv->discont |= discont; + } + + gst_adapter_push (enc->priv->adapter, buffer); + /* new stuff, so we can push subclass again */ + enc->priv->drained = FALSE; + + ret = gst_base_audio_encoder_push_buffers (enc, FALSE); + +done: + GST_LOG_OBJECT (enc, "chain leaving"); + return ret; + + /* ERRORS */ +not_negotiated: + { + GST_ELEMENT_ERROR (enc, CORE, NEGOTIATION, (NULL), + ("encoder not initialized")); + gst_buffer_unref (buffer); + return GST_FLOW_NOT_NEGOTIATED; + } +wrong_buffer: + { + GST_ELEMENT_ERROR (enc, STREAM, ENCODE, (NULL), + ("buffer size %d not a multiple of %d", GST_BUFFER_SIZE (buffer), + ctx->info.bpf)); + gst_buffer_unref (buffer); + return GST_FLOW_ERROR; + } +} + +static gboolean +audio_info_is_equal (GstAudioInfo * from, GstAudioInfo * to) +{ + if (from == to) + return TRUE; + if (GST_AUDIO_INFO_FORMAT (from) != GST_AUDIO_INFO_FORMAT (to)) + return FALSE; + if (GST_AUDIO_INFO_RATE (from) != GST_AUDIO_INFO_RATE (to)) + return FALSE; + if (GST_AUDIO_INFO_CHANNELS (from) != GST_AUDIO_INFO_CHANNELS (to)) + return FALSE; + if (GST_AUDIO_INFO_CHANNELS (from) > 64) + return TRUE; + return memcmp (from->position, to->position, + GST_AUDIO_INFO_CHANNELS (from) * sizeof (to->position[0])); +} + +static gboolean +gst_base_audio_encoder_sink_setcaps (GstPad * pad, GstCaps * caps) +{ + GstBaseAudioEncoder *enc; + GstBaseAudioEncoderClass *klass; + GstBaseAudioEncoderContext *ctx; + GstAudioInfo *state, *old_state; + gboolean res = TRUE, changed = FALSE; + guint old_rate; + + enc = GST_BASE_AUDIO_ENCODER (GST_PAD_PARENT (pad)); + klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc); + + /* subclass must do something here ... */ + g_return_val_if_fail (klass->set_format != NULL, FALSE); + + ctx = &enc->priv->ctx; + state = &ctx->info; + + GST_DEBUG_OBJECT (enc, "caps: %" GST_PTR_FORMAT, caps); + + if (!gst_caps_is_fixed (caps)) + goto refuse_caps; + + /* adjust ts tracking to new sample rate */ + old_rate = GST_AUDIO_INFO_RATE (state); + if (GST_CLOCK_TIME_IS_VALID (enc->priv->base_ts) && old_rate) { + enc->priv->base_ts += + GST_FRAMES_TO_CLOCK_TIME (enc->priv->samples, old_rate); + enc->priv->samples = 0; + } + + old_state = gst_audio_info_copy (state); + if (!gst_audio_info_from_caps (state, caps)) + goto refuse_caps; + + changed = audio_info_is_equal (state, old_state); + gst_audio_info_free (old_state); + + if (changed) { + GstClockTime old_min_latency; + GstClockTime old_max_latency; + + /* drain any pending old data stuff */ + gst_base_audio_encoder_drain (enc); + + /* context defaults */ + enc->priv->ctx.frame_samples = 0; + enc->priv->ctx.frame_max = 0; + enc->priv->ctx.lookahead = 0; + + /* element might report latency */ + GST_OBJECT_LOCK (enc); + old_min_latency = ctx->min_latency; + old_max_latency = ctx->max_latency; + GST_OBJECT_UNLOCK (enc); + + if (klass->set_format) + res = klass->set_format (enc, state); + + /* notify if new latency */ + GST_OBJECT_LOCK (enc); + if ((ctx->min_latency > 0 && ctx->min_latency != old_min_latency) || + (ctx->max_latency > 0 && ctx->max_latency != old_max_latency)) { + GST_OBJECT_UNLOCK (enc); + /* post latency message on the bus */ + gst_element_post_message (GST_ELEMENT (enc), + gst_message_new_latency (GST_OBJECT (enc))); + GST_OBJECT_LOCK (enc); + } + GST_OBJECT_UNLOCK (enc); + } else { + GST_DEBUG_OBJECT (enc, "new audio format identical to configured format"); + } + + return res; + + /* ERRORS */ +refuse_caps: + { + GST_WARNING_OBJECT (enc, "rejected caps %" GST_PTR_FORMAT, caps); + return res; + } +} + + +/** + * gst_base_audio_encoder_proxy_getcaps: + * @enc: a #GstBaseAudioEncoder + * @caps: initial caps + * + * Returns caps that express @caps (or sink template caps if @caps == NULL) + * restricted to channel/rate combinations supported by downstream elements + * (e.g. muxers). + * + * Returns: a #GstCaps owned by caller + * + * Since: 0.10.36 + */ +GstCaps * +gst_base_audio_encoder_proxy_getcaps (GstBaseAudioEncoder * enc, GstCaps * caps) +{ + const GstCaps *templ_caps; + GstCaps *allowed = NULL; + GstCaps *fcaps, *filter_caps; + gint i, j; + + /* we want to be able to communicate to upstream elements like audioconvert + * and audioresample any rate/channel restrictions downstream (e.g. muxer + * only accepting certain sample rates) */ + templ_caps = caps ? caps : gst_pad_get_pad_template_caps (enc->sinkpad); + allowed = gst_pad_get_allowed_caps (enc->srcpad); + if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) { + fcaps = gst_caps_copy (templ_caps); + goto done; + } + + GST_LOG_OBJECT (enc, "template caps %" GST_PTR_FORMAT, templ_caps); + GST_LOG_OBJECT (enc, "allowed caps %" GST_PTR_FORMAT, allowed); + + filter_caps = gst_caps_new_empty (); + + for (i = 0; i < gst_caps_get_size (templ_caps); i++) { + GQuark q_name; + + q_name = gst_structure_get_name_id (gst_caps_get_structure (templ_caps, i)); + + /* pick rate + channel fields from allowed caps */ + for (j = 0; j < gst_caps_get_size (allowed); j++) { + const GstStructure *allowed_s = gst_caps_get_structure (allowed, j); + const GValue *val; + GstStructure *s; + + s = gst_structure_id_empty_new (q_name); + if ((val = gst_structure_get_value (allowed_s, "rate"))) + gst_structure_set_value (s, "rate", val); + if ((val = gst_structure_get_value (allowed_s, "channels"))) + gst_structure_set_value (s, "channels", val); + + gst_caps_merge_structure (filter_caps, s); + } + } + + fcaps = gst_caps_intersect (filter_caps, templ_caps); + gst_caps_unref (filter_caps); + +done: + gst_caps_replace (&allowed, NULL); + + GST_LOG_OBJECT (enc, "proxy caps %" GST_PTR_FORMAT, fcaps); + + return fcaps; +} + +static GstCaps * +gst_base_audio_encoder_sink_getcaps (GstPad * pad) +{ + GstBaseAudioEncoder *enc; + GstBaseAudioEncoderClass *klass; + GstCaps *caps; + + enc = GST_BASE_AUDIO_ENCODER (gst_pad_get_parent (pad)); + klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc); + g_assert (pad == enc->sinkpad); + + if (klass->getcaps) + caps = klass->getcaps (enc); + else + caps = gst_base_audio_encoder_proxy_getcaps (enc, NULL); + gst_object_unref (enc); + + GST_LOG_OBJECT (enc, "returning caps %" GST_PTR_FORMAT, caps); + + return caps; +} + +static gboolean +gst_base_audio_encoder_sink_eventfunc (GstBaseAudioEncoder * enc, + GstEvent * event) +{ + GstBaseAudioEncoderClass *klass; + gboolean handled = FALSE; + + klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc); + + switch (GST_EVENT_TYPE (event)) { + case GST_EVENT_NEWSEGMENT: + { + GstFormat format; + gdouble rate, arate; + gint64 start, stop, time; + gboolean update; + + gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format, + &start, &stop, &time); + + if (format == GST_FORMAT_TIME) { + GST_DEBUG_OBJECT (enc, "received TIME NEW_SEGMENT %" GST_TIME_FORMAT + " -- %" GST_TIME_FORMAT ", time %" GST_TIME_FORMAT + ", rate %g, applied_rate %g", + GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (time), + rate, arate); + } else { + GST_DEBUG_OBJECT (enc, "received NEW_SEGMENT %" G_GINT64_FORMAT + " -- %" G_GINT64_FORMAT ", time %" G_GINT64_FORMAT + ", rate %g, applied_rate %g", start, stop, time, rate, arate); + GST_DEBUG_OBJECT (enc, "unsupported format; ignoring"); + break; + } + + /* finish current segment */ + gst_base_audio_encoder_drain (enc); + /* reset partially for new segment */ + gst_base_audio_encoder_reset (enc, FALSE); + /* and follow along with segment */ + gst_segment_set_newsegment_full (&enc->segment, update, rate, arate, + format, start, stop, time); + break; + } + + case GST_EVENT_FLUSH_START: + break; + + case GST_EVENT_FLUSH_STOP: + /* discard any pending stuff */ + /* TODO route through drain ?? */ + if (!enc->priv->drained && klass->flush) + klass->flush (enc); + /* and get (re)set for the sequel */ + gst_base_audio_encoder_reset (enc, FALSE); + break; + + case GST_EVENT_EOS: + gst_base_audio_encoder_drain (enc); + break; + + default: + break; + } + + return handled; +} + +static gboolean +gst_base_audio_encoder_sink_event (GstPad * pad, GstEvent * event) +{ + GstBaseAudioEncoder *enc; + GstBaseAudioEncoderClass *klass; + gboolean handled = FALSE; + gboolean ret = TRUE; + + enc = GST_BASE_AUDIO_ENCODER (gst_pad_get_parent (pad)); + klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc); + + GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event), + GST_EVENT_TYPE_NAME (event)); + + if (klass->event) + handled = klass->event (enc, event); + + if (!handled) + handled = gst_base_audio_encoder_sink_eventfunc (enc, event); + + if (!handled) + ret = gst_pad_event_default (pad, event); + + GST_DEBUG_OBJECT (enc, "event handled"); + + gst_object_unref (enc); + return ret; +} + +static gboolean +gst_base_audio_encoder_sink_query (GstPad * pad, GstQuery * query) +{ + gboolean res = TRUE; + GstBaseAudioEncoder *enc; + + enc = GST_BASE_AUDIO_ENCODER (gst_pad_get_parent (pad)); + + switch (GST_QUERY_TYPE (query)) { + case GST_QUERY_FORMATS: + { + gst_query_set_formats (query, 3, + GST_FORMAT_TIME, GST_FORMAT_BYTES, GST_FORMAT_DEFAULT); + res = TRUE; + break; + } + case GST_QUERY_CONVERT: + { + GstFormat src_fmt, dest_fmt; + gint64 src_val, dest_val; + + gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val); + if (!(res = gst_audio_info_convert (&enc->priv->ctx.info, + src_fmt, src_val, dest_fmt, &dest_val))) + goto error; + gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val); + break; + } + default: + res = gst_pad_query_default (pad, query); + break; + } + +error: + gst_object_unref (enc); + return res; +} + +static const GstQueryType * +gst_base_audio_encoder_get_query_types (GstPad * pad) +{ + static const GstQueryType gst_base_audio_encoder_src_query_types[] = { + GST_QUERY_POSITION, + GST_QUERY_DURATION, + GST_QUERY_CONVERT, + GST_QUERY_LATENCY, + 0 + }; + + return gst_base_audio_encoder_src_query_types; +} + +/* + * gst_base_audio_encoded_audio_convert: + * @fmt: audio format of the encoded audio + * @bytes: number of encoded bytes + * @samples: number of encoded samples + * @src_format: source format + * @src_value: source value + * @dest_format: destination format + * @dest_value: destination format + * + * Helper function to convert @src_value in @src_format to @dest_value in + * @dest_format for encoded audio data. Conversion is possible between + * BYTE and TIME format by using estimated bitrate based on + * @samples and @bytes (and @fmt). + * + * Since: 0.10.36 + */ +/* FIXME: make gst_base_audio_encoded_audio_convert() public? */ +static gboolean +gst_base_audio_encoded_audio_convert (GstAudioInfo * fmt, + gint64 bytes, gint64 samples, GstFormat src_format, + gint64 src_value, GstFormat * dest_format, gint64 * dest_value) +{ + gboolean res = FALSE; + + g_return_val_if_fail (dest_format != NULL, FALSE); + g_return_val_if_fail (dest_value != NULL, FALSE); + + if (G_UNLIKELY (src_format == *dest_format || src_value == 0 || + src_value == -1)) { + if (dest_value) + *dest_value = src_value; + return TRUE; + } + + if (samples == 0 || bytes == 0 || fmt->rate == 0) { + GST_DEBUG ("not enough metadata yet to convert"); + goto exit; + } + + bytes *= fmt->rate; + + switch (src_format) { + case GST_FORMAT_BYTES: + switch (*dest_format) { + case GST_FORMAT_TIME: + *dest_value = gst_util_uint64_scale (src_value, + GST_SECOND * samples, bytes); + res = TRUE; + break; + default: + res = FALSE; + } + break; + case GST_FORMAT_TIME: + switch (*dest_format) { + case GST_FORMAT_BYTES: + *dest_value = gst_util_uint64_scale (src_value, bytes, + samples * GST_SECOND); + res = TRUE; + break; + default: + res = FALSE; + } + break; + default: + res = FALSE; + } + +exit: + return res; +} + +/* FIXME ? are any of these queries (other than latency) an encoder's business + * also, the conversion stuff might seem to make sense, but seems to not mind + * segment stuff etc at all + * Supposedly that's backward compatibility ... */ +static gboolean +gst_base_audio_encoder_src_query (GstPad * pad, GstQuery * query) +{ + GstBaseAudioEncoder *enc; + GstPad *peerpad; + gboolean res = FALSE; + + enc = GST_BASE_AUDIO_ENCODER (GST_PAD_PARENT (pad)); + peerpad = gst_pad_get_peer (GST_PAD (enc->sinkpad)); + + GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query); + + switch (GST_QUERY_TYPE (query)) { + case GST_QUERY_POSITION: + { + GstFormat fmt, req_fmt; + gint64 pos, val; + + if ((res = gst_pad_peer_query (enc->sinkpad, query))) { + GST_LOG_OBJECT (enc, "returning peer response"); + break; + } + + if (!peerpad) { + GST_LOG_OBJECT (enc, "no peer"); + break; + } + + gst_query_parse_position (query, &req_fmt, NULL); + fmt = GST_FORMAT_TIME; + if (!(res = gst_pad_query_position (peerpad, &fmt, &pos))) + break; + + if ((res = gst_pad_query_convert (peerpad, fmt, pos, &req_fmt, &val))) { + gst_query_set_position (query, req_fmt, val); + } + break; + } + case GST_QUERY_DURATION: + { + GstFormat fmt, req_fmt; + gint64 dur, val; + + if ((res = gst_pad_peer_query (enc->sinkpad, query))) { + GST_LOG_OBJECT (enc, "returning peer response"); + break; + } + + if (!peerpad) { + GST_LOG_OBJECT (enc, "no peer"); + break; + } + + gst_query_parse_duration (query, &req_fmt, NULL); + fmt = GST_FORMAT_TIME; + if (!(res = gst_pad_query_duration (peerpad, &fmt, &dur))) + break; + + if ((res = gst_pad_query_convert (peerpad, fmt, dur, &req_fmt, &val))) { + gst_query_set_duration (query, req_fmt, val); + } + break; + } + case GST_QUERY_FORMATS: + { + gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES); + res = TRUE; + break; + } + case GST_QUERY_CONVERT: + { + GstFormat src_fmt, dest_fmt; + gint64 src_val, dest_val; + + gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val); + if (!(res = gst_base_audio_encoded_audio_convert (&enc->priv->ctx.info, + enc->priv->bytes_out, enc->priv->samples_in, src_fmt, src_val, + &dest_fmt, &dest_val))) + break; + gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val); + break; + } + case GST_QUERY_LATENCY: + { + if ((res = gst_pad_peer_query (enc->sinkpad, query))) { + gboolean live; + GstClockTime min_latency, max_latency; + + gst_query_parse_latency (query, &live, &min_latency, &max_latency); + GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %" + GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live, + GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency)); + + GST_OBJECT_LOCK (enc); + /* add our latency */ + if (min_latency != -1) + min_latency += enc->priv->ctx.min_latency; + if (max_latency != -1) + max_latency += enc->priv->ctx.max_latency; + GST_OBJECT_UNLOCK (enc); + + gst_query_set_latency (query, live, min_latency, max_latency); + } + break; + } + default: + res = gst_pad_query_default (pad, query); + break; + } + + gst_object_unref (peerpad); + return res; +} + +static void +gst_base_audio_encoder_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstBaseAudioEncoder *enc; + + enc = GST_BASE_AUDIO_ENCODER (object); + + switch (prop_id) { + case PROP_PERFECT_TS: + if (enc->priv->granule && !g_value_get_boolean (value)) + GST_WARNING_OBJECT (enc, "perfect-ts can not be set FALSE"); + else + enc->priv->perfect_ts = g_value_get_boolean (value); + break; + case PROP_HARD_RESYNC: + enc->priv->hard_resync = g_value_get_boolean (value); + break; + case PROP_TOLERANCE: + enc->priv->tolerance = g_value_get_int64 (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_base_audio_encoder_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec) +{ + GstBaseAudioEncoder *enc; + + enc = GST_BASE_AUDIO_ENCODER (object); + + switch (prop_id) { + case PROP_PERFECT_TS: + g_value_set_boolean (value, enc->priv->perfect_ts); + break; + case PROP_GRANULE: + g_value_set_boolean (value, enc->priv->granule); + break; + case PROP_HARD_RESYNC: + g_value_set_boolean (value, enc->priv->hard_resync); + break; + case PROP_TOLERANCE: + g_value_set_int64 (value, enc->priv->tolerance); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static gboolean +gst_base_audio_encoder_activate (GstBaseAudioEncoder * enc, gboolean active) +{ + GstBaseAudioEncoderClass *klass; + gboolean result = FALSE; + + klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc); + + g_return_val_if_fail (!enc->priv->granule || enc->priv->perfect_ts, FALSE); + + GST_DEBUG_OBJECT (enc, "activate %d", active); + + if (active) { + if (!enc->priv->active && klass->start) + result = klass->start (enc); + } else { + /* We must make sure streaming has finished before resetting things + * and calling the ::stop vfunc */ + GST_PAD_STREAM_LOCK (enc->sinkpad); + GST_PAD_STREAM_UNLOCK (enc->sinkpad); + + if (enc->priv->active && klass->stop) + result = klass->stop (enc); + + /* clean up */ + gst_base_audio_encoder_reset (enc, TRUE); + } + GST_DEBUG_OBJECT (enc, "activate return: %d", result); + return result; +} + + +static gboolean +gst_base_audio_encoder_sink_activate_push (GstPad * pad, gboolean active) +{ + gboolean result = TRUE; + GstBaseAudioEncoder *enc; + + enc = GST_BASE_AUDIO_ENCODER (gst_pad_get_parent (pad)); + + GST_DEBUG_OBJECT (enc, "sink activate push %d", active); + + result = gst_base_audio_encoder_activate (enc, active); + + if (result) + enc->priv->active = active; + + GST_DEBUG_OBJECT (enc, "sink activate push return: %d", result); + + gst_object_unref (enc); + return result; +} + +/** + * gst_base_audio_encoder_get_audio_info: + * @enc: a #GstBaseAudioEncoder + * + * Returns: a #GstAudioInfo describing the input audio format + * + * Since: 0.10.36 + */ +GstAudioInfo * +gst_base_audio_encoder_get_audio_info (GstBaseAudioEncoder * enc) +{ + g_return_val_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc), NULL); + + return &enc->priv->ctx.info; +} + +/** + * gst_base_audio_encoder_set_frame_samples: + * @enc: a #GstBaseAudioEncoder + * @num: number of samples per frame + * + * Sets number of samples (per channel) subclass needs to be handed, + * or will be handed all available if 0. + * + * Since: 0.10.36 + */ +void +gst_base_audio_encoder_set_frame_samples (GstBaseAudioEncoder * enc, gint num) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc)); + + enc->priv->ctx.frame_samples = num; +} + +/** + * gst_base_audio_encoder_get_frame_samples: + * @enc: a #GstBaseAudioEncoder + * + * Returns: currently requested samples per frame + * + * Since: 0.10.36 + */ +gint +gst_base_audio_encoder_get_frame_samples (GstBaseAudioEncoder * enc) +{ + g_return_val_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc), 0); + + return enc->priv->ctx.frame_samples; +} + +/** + * gst_base_audio_encoder_set_frame_max: + * @enc: a #GstBaseAudioEncoder + * @num: number of frames + * + * Sets max number of frames accepted at once (assumed minimally 1) + * + * Since: 0.10.36 + */ +void +gst_base_audio_encoder_set_frame_max (GstBaseAudioEncoder * enc, gint num) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc)); + + enc->priv->ctx.frame_max = num; +} + +/** + * gst_base_audio_encoder_get_frame_max: + * @enc: a #GstBaseAudioEncoder + * + * Returns: currently configured maximum handled frames + * + * Since: 0.10.36 + */ +gint +gst_base_audio_encoder_get_frame_max (GstBaseAudioEncoder * enc) +{ + g_return_val_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc), 0); + + return enc->priv->ctx.frame_max; +} + +/** + * gst_base_audio_encoder_set_lookahead: + * @enc: a #GstBaseAudioEncoder + * @num: lookahead + * + * Sets encoder lookahead (in units of input rate samples) + * + * Since: 0.10.36 + */ +void +gst_base_audio_encoder_set_lookahead (GstBaseAudioEncoder * enc, gint num) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc)); + + enc->priv->ctx.lookahead = num; +} + +/** + * gst_base_audio_encoder_get_lookahead: + * @enc: a #GstBaseAudioEncoder + * + * Returns: currently configured encoder lookahead + */ +gint +gst_base_audio_encoder_get_lookahead (GstBaseAudioEncoder * enc) +{ + g_return_val_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc), 0); + + return enc->priv->ctx.lookahead; +} + +/** + * gst_base_audio_encoder_set_latency: + * @enc: a #GstBaseAudioEncoder + * @min: minimum latency + * @max: maximum latency + * + * Sets encoder latency. + * + * Since: 0.10.36 + */ +void +gst_base_audio_encoder_set_latency (GstBaseAudioEncoder * enc, + GstClockTime min, GstClockTime max) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc)); + + GST_OBJECT_LOCK (enc); + enc->priv->ctx.min_latency = min; + enc->priv->ctx.max_latency = max; + GST_OBJECT_UNLOCK (enc); +} + +/** + * gst_base_audio_encoder_get_latency: + * @enc: a #GstBaseAudioEncoder + * @min: a pointer to storage to hold minimum latency + * @max: a pointer to storage to hold maximum latency + * + * Returns currently configured latency. + * + * Since: 0.10.36 + */ +void +gst_base_audio_encoder_get_latency (GstBaseAudioEncoder * enc, + GstClockTime * min, GstClockTime * max) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc)); + + GST_OBJECT_LOCK (enc); + if (min) + *min = enc->priv->ctx.min_latency; + if (max) + *max = enc->priv->ctx.max_latency; + GST_OBJECT_UNLOCK (enc); +} + +/** + * gst_base_audio_encoder_set_mark_granule: + * @enc: a #GstBaseAudioEncoder + * @enabled: new state + * + * Enable or disable encoder granule handling. + * + * MT safe. + * + * Since: 0.10.36 + */ +void +gst_base_audio_encoder_set_mark_granule (GstBaseAudioEncoder * enc, + gboolean enabled) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc)); + + GST_LOG_OBJECT (enc, "enabled: %d", enabled); + + GST_OBJECT_LOCK (enc); + enc->priv->granule = enabled; + GST_OBJECT_UNLOCK (enc); +} + +/** + * gst_base_audio_encoder_get_mark_granule: + * @enc: a #GstBaseAudioEncoder + * + * Queries if the encoder will handle granule marking. + * + * Returns: TRUE if granule marking is enabled. + * + * MT safe. + * + * Since: 0.10.36 + */ +gboolean +gst_base_audio_encoder_get_mark_granule (GstBaseAudioEncoder * enc) +{ + gboolean result; + + g_return_val_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc), FALSE); + + GST_OBJECT_LOCK (enc); + result = enc->priv->granule; + GST_OBJECT_UNLOCK (enc); + + return result; +} + +/** + * gst_base_audio_encoder_set_perfect_timestamp: + * @enc: a #GstBaseAudioEncoder + * @enabled: new state + * + * Enable or disable encoder perfect output timestamp preference. + * + * MT safe. + * + * Since: 0.10.36 + */ +void +gst_base_audio_encoder_set_perfect_timestamp (GstBaseAudioEncoder * enc, + gboolean enabled) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc)); + + GST_LOG_OBJECT (enc, "enabled: %d", enabled); + + GST_OBJECT_LOCK (enc); + enc->priv->perfect_ts = enabled; + GST_OBJECT_UNLOCK (enc); +} + +/** + * gst_base_audio_encoder_get_perfect_timestamp: + * @enc: a #GstBaseAudioEncoder + * + * Queries encoder perfect timestamp behaviour. + * + * Returns: TRUE if pefect timestamp setting enabled. + * + * MT safe. + * + * Since: 0.10.36 + */ +gboolean +gst_base_audio_encoder_get_perfect_timestamp (GstBaseAudioEncoder * enc) +{ + gboolean result; + + g_return_val_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc), FALSE); + + GST_OBJECT_LOCK (enc); + result = enc->priv->perfect_ts; + GST_OBJECT_UNLOCK (enc); + + return result; +} + +/** + * gst_base_audio_encoder_set_hard_sync: + * @enc: a #GstBaseAudioEncoder + * @enabled: new state + * + * Sets encoder hard resync handling. + * + * MT safe. + * + * Since: 0.10.36 + */ +void +gst_base_audio_encoder_set_hard_resync (GstBaseAudioEncoder * enc, + gboolean enabled) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc)); + + GST_LOG_OBJECT (enc, "enabled: %d", enabled); + + GST_OBJECT_LOCK (enc); + enc->priv->hard_resync = enabled; + GST_OBJECT_UNLOCK (enc); +} + +/** + * gst_base_audio_encoder_get_hard_sync: + * @enc: a #GstBaseAudioEncoder + * + * Queries encoder's hard resync setting. + * + * Returns: TRUE if hard resync is enabled. + * + * MT safe. + * + * Since: 0.10.36 + */ +gboolean +gst_base_audio_encoder_get_hard_resync (GstBaseAudioEncoder * enc) +{ + gboolean result; + + g_return_val_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc), FALSE); + + GST_OBJECT_LOCK (enc); + result = enc->priv->hard_resync; + GST_OBJECT_UNLOCK (enc); + + return result; +} + +/** + * gst_base_audio_encoder_set_tolerance: + * @enc: a #GstBaseAudioEncoder + * @tolerance: new tolerance + * + * Configures encoder audio jitter tolerance threshold. + * + * MT safe. + * + * Since: 0.10.36 + */ +void +gst_base_audio_encoder_set_tolerance (GstBaseAudioEncoder * enc, + gint64 tolerance) +{ + g_return_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc)); + + GST_OBJECT_LOCK (enc); + enc->priv->tolerance = tolerance; + GST_OBJECT_UNLOCK (enc); +} + +/** + * gst_base_audio_encoder_get_tolerance: + * @enc: a #GstBaseAudioEncoder + * + * Queries current audio jitter tolerance threshold. + * + * Returns: encoder audio jitter tolerance threshold. + * + * MT safe. + * + * Since: 0.10.36 + */ +gint64 +gst_base_audio_encoder_get_tolerance (GstBaseAudioEncoder * enc) +{ + gint64 result; + + g_return_val_if_fail (GST_IS_BASE_AUDIO_ENCODER (enc), 0); + + GST_OBJECT_LOCK (enc); + result = enc->priv->tolerance; + GST_OBJECT_UNLOCK (enc); + + return result; +} diff --git a/gst-libs/gst/audio/gstbaseaudioencoder.h b/gst-libs/gst/audio/gstbaseaudioencoder.h new file mode 100644 index 000000000..fa948daff --- /dev/null +++ b/gst-libs/gst/audio/gstbaseaudioencoder.h @@ -0,0 +1,235 @@ +/* GStreamer + * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>. + * Copyright (C) 2011 Nokia Corporation. All rights reserved. + * Contact: Stefan Kost <stefan.kost@nokia.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifndef __GST_BASE_AUDIO_ENCODER_H__ +#define __GST_BASE_AUDIO_ENCODER_H__ + +#ifndef GST_USE_UNSTABLE_API +#warning "GstBaseAudioEncoder is unstable API and may change in future." +#warning "You can define GST_USE_UNSTABLE_API to avoid this warning." +#endif + +#include <gst/gst.h> +#include <gst/audio/audio.h> + +G_BEGIN_DECLS + +#define GST_TYPE_BASE_AUDIO_ENCODER (gst_base_audio_encoder_get_type()) +#define GST_BASE_AUDIO_ENCODER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_BASE_AUDIO_ENCODER,GstBaseAudioEncoder)) +#define GST_BASE_AUDIO_ENCODER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_BASE_AUDIO_ENCODER,GstBaseAudioEncoderClass)) +#define GST_BASE_AUDIO_ENCODER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj),GST_TYPE_BASE_AUDIO_ENCODER,GstBaseAudioEncoderClass)) +#define GST_IS_BASE_AUDIO_ENCODER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_BASE_AUDIO_ENCODER)) +#define GST_IS_BASE_AUDIO_ENCODER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_BASE_AUDIO_ENCODER)) +#define GST_BASE_AUDIO_ENCODER_CAST(obj) ((GstBaseAudioEncoder *)(obj)) + +/** + * GST_BASE_AUDIO_ENCODER_SINK_NAME: + * + * the name of the templates for the sink pad + * + * Since: 0.10.36 + */ +#define GST_BASE_AUDIO_ENCODER_SINK_NAME "sink" +/** + * GST_BASE_AUDIO_ENCODER_SRC_NAME: + * + * the name of the templates for the source pad + * + * Since: 0.10.36 + */ +#define GST_BASE_AUDIO_ENCODER_SRC_NAME "src" + +/** + * GST_BASE_AUDIO_ENCODER_SRC_PAD: + * @obj: base parse instance + * + * Gives the pointer to the source #GstPad object of the element. + * + * Since: 0.10.36 + */ +#define GST_BASE_AUDIO_ENCODER_SRC_PAD(obj) (GST_BASE_AUDIO_ENCODER_CAST (obj)->srcpad) + +/** + * GST_BASE_AUDIO_ENCODER_SINK_PAD: + * @obj: base parse instance + * + * Gives the pointer to the sink #GstPad object of the element. + * + * Since: 0.10.36 + */ +#define GST_BASE_AUDIO_ENCODER_SINK_PAD(obj) (GST_BASE_AUDIO_ENCODER_CAST (obj)->sinkpad) + +/** + * GST_BASE_AUDIO_ENCODER_SEGMENT: + * @obj: base parse instance + * + * Gives the segment of the element. + * + * Since: 0.10.36 + */ +#define GST_BASE_AUDIO_ENCODER_SEGMENT(obj) (GST_BASE_AUDIO_ENCODER_CAST (obj)->segment) + + +typedef struct _GstBaseAudioEncoder GstBaseAudioEncoder; +typedef struct _GstBaseAudioEncoderClass GstBaseAudioEncoderClass; + +typedef struct _GstBaseAudioEncoderPrivate GstBaseAudioEncoderPrivate; + +/** + * GstBaseAudioEncoder: + * @element: the parent element. + * + * The opaque #GstBaseAudioEncoder data structure. + * + * Since: 0.10.36 + */ +struct _GstBaseAudioEncoder { + GstElement element; + + /*< protected >*/ + /* source and sink pads */ + GstPad *sinkpad; + GstPad *srcpad; + + /* MT-protected (with STREAM_LOCK) */ + GstSegment segment; + + /*< private >*/ + GstBaseAudioEncoderPrivate *priv; + gpointer _gst_reserved[GST_PADDING_LARGE]; +}; + +/** + * GstBaseAudioEncoderClass: + * @start: Optional. + * Called when the element starts processing. + * Allows opening external resources. + * @stop: Optional. + * Called when the element stops processing. + * Allows closing external resources. + * @set_format: Notifies subclass of incoming data format. + * GstAudioInfo contains the format according to provided caps. + * @handle_frame: Provides input samples (or NULL to clear any remaining data) + * according to directions as provided by subclass in the + * #GstBaseAudioEncoderContext. Input data ref management + * is performed by base class, subclass should not care or + * intervene. + * @flush: Optional. + * Instructs subclass to clear any codec caches and discard + * any pending samples and not yet returned encoded data. + * @event: Optional. + * Event handler on the sink pad. This function should return + * TRUE if the event was handled and should be discarded + * (i.e. not unref'ed). + * @pre_push: Optional. + * Called just prior to pushing (encoded data) buffer downstream. + * Subclass has full discretionary access to buffer, + * and a not OK flow return will abort downstream pushing. + * @getcaps: Optional. + * Allows for a custom sink getcaps implementation (e.g. + * for multichannel input specification). If not implemented, + * default returns gst_base_audio_encoder_proxy_getcaps + * applied to sink template caps. + * + * Subclasses can override any of the available virtual methods or not, as + * needed. At minimum @set_format and @handle_frame needs to be overridden. + * + * Since: 0.10.36 + */ +struct _GstBaseAudioEncoderClass { + GstElementClass parent_class; + + /*< public >*/ + /* virtual methods for subclasses */ + + gboolean (*start) (GstBaseAudioEncoder *enc); + + gboolean (*stop) (GstBaseAudioEncoder *enc); + + gboolean (*set_format) (GstBaseAudioEncoder *enc, + GstAudioInfo *info); + + GstFlowReturn (*handle_frame) (GstBaseAudioEncoder *enc, + GstBuffer *buffer); + + void (*flush) (GstBaseAudioEncoder *enc); + + GstFlowReturn (*pre_push) (GstBaseAudioEncoder *enc, + GstBuffer **buffer); + + gboolean (*event) (GstBaseAudioEncoder *enc, + GstEvent *event); + + GstCaps * (*getcaps) (GstBaseAudioEncoder *enc); + + /*< private >*/ + gpointer _gst_reserved[GST_PADDING_LARGE]; +}; + +GType gst_base_audio_encoder_get_type (void); + +GstFlowReturn gst_base_audio_encoder_finish_frame (GstBaseAudioEncoder * enc, + GstBuffer *buffer, gint samples); + +GstCaps * gst_base_audio_encoder_proxy_getcaps (GstBaseAudioEncoder * enc, + GstCaps * caps); + + +/* context parameters */ +GstAudioInfo * gst_base_audio_encoder_get_audio_info (GstBaseAudioEncoder * enc); + +gint gst_base_audio_encoder_get_frame_samples (GstBaseAudioEncoder * enc); +void gst_base_audio_encoder_set_frame_samples (GstBaseAudioEncoder * enc, + gint num); + +gint gst_base_audio_encoder_get_frame_max (GstBaseAudioEncoder * enc); +void gst_base_audio_encoder_set_frame_max (GstBaseAudioEncoder * enc, + gint num); + +gint gst_base_audio_encoder_get_lookahead (GstBaseAudioEncoder * enc); +void gst_base_audio_encoder_set_lookahead (GstBaseAudioEncoder * enc, + gint num); + +void gst_base_audio_encoder_get_latency (GstBaseAudioEncoder * enc, + GstClockTime * min, GstClockTime * max); +void gst_base_audio_encoder_set_latency (GstBaseAudioEncoder * enc, + GstClockTime min, GstClockTime max); + +/* object properties */ +void gst_base_audio_encoder_set_mark_granule (GstBaseAudioEncoder * enc, + gboolean enabled); +gboolean gst_base_audio_encoder_get_mark_granule (GstBaseAudioEncoder * enc); + +void gst_base_audio_encoder_set_perfect_timestamp (GstBaseAudioEncoder * enc, + gboolean enabled); +gboolean gst_base_audio_encoder_get_perfect_timestamp (GstBaseAudioEncoder * enc); + +void gst_base_audio_encoder_set_hard_resync (GstBaseAudioEncoder * enc, + gboolean enabled); +gboolean gst_base_audio_encoder_get_hard_resync (GstBaseAudioEncoder * enc); + +void gst_base_audio_encoder_set_tolerance (GstBaseAudioEncoder * enc, + gint64 tolerance); +gint64 gst_base_audio_encoder_get_tolerance (GstBaseAudioEncoder * enc); + +G_END_DECLS + +#endif /* __GST_BASE_AUDIO_ENCODER_H__ */ diff --git a/gst-libs/gst/audio/multichannel.c b/gst-libs/gst/audio/multichannel.c index 388adcd8d..885e277d3 100644 --- a/gst-libs/gst/audio/multichannel.c +++ b/gst-libs/gst/audio/multichannel.c @@ -288,6 +288,32 @@ gst_audio_get_channel_positions (GstStructure * str) return pos; } +void priv_gst_audio_info_fill_default_channel_positions (GstAudioInfo * info); + +void +priv_gst_audio_info_fill_default_channel_positions (GstAudioInfo * info) +{ + guint channels, i; + + g_assert (info != NULL); + + channels = GST_AUDIO_INFO_CHANNELS (info); + + g_assert (channels > 0); + + if (channels <= NUM_DEF_CHANS) { + /* just return some default channel layout if we have one */ + for (i = 0; i < channels; ++i) + info->position[i] = default_positions[channels - 1][i]; + } else { + /* for many many channels, the positions are always NONE */ + for (i = 0; i < G_N_ELEMENTS (info->position); i++) + info->position[i] = GST_AUDIO_CHANNEL_POSITION_NONE; + } + + info->flags |= GST_AUDIO_FLAG_DEFAULT_POSITIONS; +} + /** * gst_audio_set_channel_positions: * @str: A #GstStructure to set channel positions on. diff --git a/gst-libs/gst/audio/multichannel.h b/gst-libs/gst/audio/multichannel.h index 759da3021..ab00eca53 100644 --- a/gst-libs/gst/audio/multichannel.h +++ b/gst-libs/gst/audio/multichannel.h @@ -17,12 +17,12 @@ * Boston, MA 02111-1307, USA. */ +#include <gst/audio/audio.h> +#include <gst/audio/audio-enumtypes.h> + #ifndef __GST_AUDIO_MULTICHANNEL_H__ #define __GST_AUDIO_MULTICHANNEL_H__ -#include <gst/gst.h> -#include <gst/audio/audio-enumtypes.h> - G_BEGIN_DECLS /** diff --git a/gst-libs/gst/pbutils/Makefile.am b/gst-libs/gst/pbutils/Makefile.am index abb4fcd22..16ff0538b 100644 --- a/gst-libs/gst/pbutils/Makefile.am +++ b/gst-libs/gst/pbutils/Makefile.am @@ -85,7 +85,6 @@ GstPbutils-@GST_MAJORMINOR@.gir: $(INTROSPECTION_SCANNER) libgstpbutils-@GST_MAJ -DGST_USE_UNSTABLE_API \ -I$(top_srcdir)/gst-libs \ -I$(top_builddir)/gst-libs \ - --add-include-path=$(srcdir)/../video \ --add-include-path=`$(PKG_CONFIG) --variable=girdir gstreamer-@GST_MAJORMINOR@` \ --library=libgstpbutils-@GST_MAJORMINOR@.la \ --library-path=`$(PKG_CONFIG) --variable=libdir gstreamer-@GST_MAJORMINOR@` \ @@ -93,7 +92,6 @@ GstPbutils-@GST_MAJORMINOR@.gir: $(INTROSPECTION_SCANNER) libgstpbutils-@GST_MAJ --include=Gst-@GST_MAJORMINOR@ \ --libtool="$(top_builddir)/libtool" \ --pkg gstreamer-@GST_MAJORMINOR@ \ - --pkg gstreamer-video-@GST_MAJORMINOR@ \ --pkg-export gstreamer-pbutils-@GST_MAJORMINOR@ \ --add-init-section="gst_init(NULL,NULL);" \ --output $@ \ @@ -113,7 +111,6 @@ typelibs_DATA = $(BUILT_GIRSOURCES:.gir=.typelib) $(AM_V_GEN)PKG_CONFIG_PATH="$(GST_PKG_CONFIG_PATH)" \ $(INTROSPECTION_COMPILER) \ --includedir=$(srcdir) \ - --includedir=$(srcdir)/../video \ --includedir=$(builddir) \ --includedir=`$(PKG_CONFIG) --variable=girdir gstreamer-@GST_MAJORMINOR@` \ $(INTROSPECTION_COMPILER_OPTS) $< -o $(@F) diff --git a/gst-libs/gst/pbutils/gstdiscoverer-types.c b/gst-libs/gst/pbutils/gstdiscoverer-types.c index 7dc78462a..94ba47585 100644 --- a/gst-libs/gst/pbutils/gstdiscoverer-types.c +++ b/gst-libs/gst/pbutils/gstdiscoverer-types.c @@ -39,6 +39,9 @@ static GstDiscovererAudioInfo static GstDiscovererVideoInfo * gst_discoverer_video_info_copy_int (GstDiscovererVideoInfo * ptr); +static GstDiscovererSubtitleInfo + * gst_discoverer_subtitle_info_copy_int (GstDiscovererSubtitleInfo * ptr); + /* Per-stream information */ G_DEFINE_TYPE (GstDiscovererStreamInfo, gst_discoverer_stream_info, @@ -104,6 +107,11 @@ gst_discoverer_info_copy_int (GstDiscovererStreamInfo * info, ret = (GstDiscovererStreamInfo *) gst_discoverer_video_info_copy_int ((GstDiscovererVideoInfo *) info); + } else if (ltyp == GST_TYPE_DISCOVERER_SUBTITLE_INFO) { + ret = (GstDiscovererStreamInfo *) + gst_discoverer_subtitle_info_copy_int ((GstDiscovererSubtitleInfo *) + info); + } else ret = gst_discoverer_stream_info_new (); @@ -193,15 +201,22 @@ G_DEFINE_TYPE (GstDiscovererAudioInfo, gst_discoverer_audio_info, GST_TYPE_DISCOVERER_STREAM_INFO); static void +gst_discoverer_audio_info_finalize (GstDiscovererAudioInfo * info) +{ + g_free (info->language); +} + +static void gst_discoverer_audio_info_class_init (GstDiscovererAudioInfoClass * klass) { - /* Nothing to initialize */ + klass->finalize = + (GstMiniObjectFinalizeFunction) gst_discoverer_audio_info_finalize; } static void gst_discoverer_audio_info_init (GstDiscovererAudioInfo * info) { - /* Nothing to initialize */ + info->language = NULL; } static GstDiscovererAudioInfo * @@ -223,6 +238,49 @@ gst_discoverer_audio_info_copy_int (GstDiscovererAudioInfo * ptr) ret->depth = ptr->depth; ret->bitrate = ptr->bitrate; ret->max_bitrate = ptr->max_bitrate; + ret->language = g_strdup (ptr->language); + + return ret; +} + +/* Subtitle information */ +G_DEFINE_TYPE (GstDiscovererSubtitleInfo, gst_discoverer_subtitle_info, + GST_TYPE_DISCOVERER_STREAM_INFO); + +static void +gst_discoverer_subtitle_info_init (GstDiscovererSubtitleInfo * info) +{ + info->language = NULL; +} + +static void +gst_discoverer_subtitle_info_finalize (GstDiscovererSubtitleInfo * info) +{ + g_free (info->language); +} + +static void +gst_discoverer_subtitle_info_class_init (GstMiniObjectClass * klass) +{ + klass->finalize = + (GstMiniObjectFinalizeFunction) gst_discoverer_subtitle_info_finalize; +} + +static GstDiscovererSubtitleInfo * +gst_discoverer_subtitle_info_new (void) +{ + return (GstDiscovererSubtitleInfo *) + gst_mini_object_new (GST_TYPE_DISCOVERER_SUBTITLE_INFO); +} + +static GstDiscovererSubtitleInfo * +gst_discoverer_subtitle_info_copy_int (GstDiscovererSubtitleInfo * ptr) +{ + GstDiscovererSubtitleInfo *ret; + + ret = gst_discoverer_subtitle_info_new (); + + ret->language = g_strdup (ptr->language); return ret; } @@ -433,6 +491,25 @@ gst_discoverer_info_get_video_streams (GstDiscovererInfo * info) } /** + * gst_discoverer_info_get_subtitle_streams: + * @info: a #GstDiscovererInfo + * + * Finds all the #GstDiscovererSubtitleInfo contained in @info + * + * Returns: (transfer full) (element-type Gst.DiscovererStreamInfo): A #GList of + * matching #GstDiscovererStreamInfo. The caller should free it with + * gst_discoverer_stream_info_list_free(). + * + * Since: 0.10.36 + */ +GList * +gst_discoverer_info_get_subtitle_streams (GstDiscovererInfo * info) +{ + return gst_discoverer_info_get_streams (info, + GST_TYPE_DISCOVERER_SUBTITLE_INFO); +} + +/** * gst_discoverer_info_get_container_streams: * @info: a #GstDiscovererInfo * @@ -474,6 +551,8 @@ gst_discoverer_stream_info_get_stream_type_nick (GstDiscovererStreamInfo * info) else return "video"; } + if (GST_IS_DISCOVERER_SUBTITLE_INFO (info)) + return "subtitles"; return "unknown"; } @@ -672,6 +751,17 @@ AUDIO_INFO_ACCESSOR_CODE (bitrate, guint, 0); AUDIO_INFO_ACCESSOR_CODE (max_bitrate, guint, 0); +/** + * gst_discoverer_audio_info_get_language: + * @info: a #GstDiscovererAudioInfo + * + * Returns: the language of the stream, or NULL if unknown. + * + * Since: 0.10.36 + */ + +AUDIO_INFO_ACCESSOR_CODE (language, const gchar *, NULL); + /* GstDiscovererVideoInfo */ #define VIDEO_INFO_ACCESSOR_CODE(fieldname, type, failval) \ @@ -811,6 +901,24 @@ gst_discoverer_video_info_is_image (const GstDiscovererVideoInfo * info) return info->is_image; } +/* GstDiscovererSubtitleInfo */ + +#define SUBTITLE_INFO_ACCESSOR_CODE(fieldname, type, failval) \ + GENERIC_ACCESSOR_CODE(gst_discoverer_subtitle_info, GstDiscovererSubtitleInfo*, \ + GST_TYPE_DISCOVERER_SUBTITLE_INFO, \ + fieldname, type, failval) + +/** + * gst_discoverer_subtitle_info_get_language: + * @info: a #GstDiscovererSubtitleInfo + * + * Returns: the language of the stream, or NULL if unknown. + * + * Since: 0.10.36 + */ + +SUBTITLE_INFO_ACCESSOR_CODE (language, const gchar *, NULL); + /* GstDiscovererInfo */ #define DISCOVERER_INFO_ACCESSOR_CODE(fieldname, type, failval) \ diff --git a/gst-libs/gst/pbutils/gstdiscoverer.c b/gst-libs/gst/pbutils/gstdiscoverer.c index bdbcb261e..05bd86ec3 100644 --- a/gst-libs/gst/pbutils/gstdiscoverer.c +++ b/gst-libs/gst/pbutils/gstdiscoverer.c @@ -44,7 +44,6 @@ #include "config.h" #endif -#include <gst/video/video.h> #include "pbutils.h" #include "pbutils-marshal.h" #include "pbutils-private.h" @@ -438,22 +437,29 @@ _event_probe (GstPad * pad, GstProbeType type, GstEvent * event, return GST_PROBE_OK; } -static void -uridecodebin_pad_added_cb (GstElement * uridecodebin, GstPad * pad, - GstDiscoverer * dc) +static gboolean +is_subtitle_caps (const GstCaps * caps) { - PrivateStream *ps; - GstPad *sinkpad = NULL; - GstCaps *caps; static GstCaps *subs_caps = NULL; if (!subs_caps) { subs_caps = gst_caps_from_string ("text/plain; text/x-pango-markup; " "subpicture/x-pgs; subpicture/x-dvb; application/x-subtitle-unknown; " "application/x-ssa; application/x-ass; subtitle/x-kate; " - "video/x-dvd-subpicture; "); + "application/x-kate; video/x-dvd-subpicture; "); } + return gst_caps_can_intersect (caps, subs_caps); +} + +static void +uridecodebin_pad_added_cb (GstElement * uridecodebin, GstPad * pad, + GstDiscoverer * dc) +{ + PrivateStream *ps; + GstPad *sinkpad = NULL; + GstCaps *caps; + GST_DEBUG_OBJECT (dc, "pad %s:%s", GST_DEBUG_PAD_NAME (pad)); ps = g_slice_new0 (PrivateStream); @@ -471,8 +477,8 @@ uridecodebin_pad_added_cb (GstElement * uridecodebin, GstPad * pad, caps = gst_pad_get_caps (pad, NULL); - if (gst_caps_can_intersect (caps, subs_caps)) { - /* Subtitle streams are sparse and don't provide any information - don't + if (is_subtitle_caps (caps)) { + /* Subtitle streams are sparse and may not provide any information - don't * wait for data to preroll */ g_object_set (ps->sink, "async", FALSE, NULL); } @@ -661,6 +667,14 @@ collect_information (GstDiscoverer * dc, const GstStructure * st, gst_structure_free (tags_st); } + if (!info->language && ((GstDiscovererStreamInfo *) info)->tags) { + gchar *language; + if (gst_tag_list_get_string (((GstDiscovererStreamInfo *) info)->tags, + GST_TAG_LANGUAGE_CODE, &language)) { + info->language = language; + } + } + return (GstDiscovererStreamInfo *) info; } else if (g_str_has_prefix (name, "video/") || @@ -709,6 +723,44 @@ collect_information (GstDiscoverer * dc, const GstStructure * st, return (GstDiscovererStreamInfo *) info; + } else if (is_subtitle_caps (caps)) { + GstDiscovererSubtitleInfo *info; + + if (parent) + info = (GstDiscovererSubtitleInfo *) parent; + else { + info = (GstDiscovererSubtitleInfo *) + gst_mini_object_new (GST_TYPE_DISCOVERER_SUBTITLE_INFO); + info->parent.caps = caps; + } + + if (gst_structure_id_has_field (st, _TAGS_QUARK)) { + const gchar *language; + + gst_structure_id_get (st, _TAGS_QUARK, + GST_TYPE_STRUCTURE, &tags_st, NULL); + + language = gst_structure_get_string (caps_st, GST_TAG_LANGUAGE_CODE); + if (language) + info->language = g_strdup (language); + + /* FIXME: Is it worth it to remove the tags we've parsed? */ + info->parent.tags = gst_tag_list_merge (info->parent.tags, + (GstTagList *) tags_st, GST_TAG_MERGE_REPLACE); + gst_structure_free (tags_st); + + } + + if (!info->language && ((GstDiscovererStreamInfo *) info)->tags) { + gchar *language; + if (gst_tag_list_get_string (((GstDiscovererStreamInfo *) info)->tags, + GST_TAG_LANGUAGE_CODE, &language)) { + info->language = language; + } + } + + return (GstDiscovererStreamInfo *) info; + } else { /* None of the above - populate what information we can */ GstDiscovererStreamInfo *info; @@ -792,6 +844,9 @@ child_is_raw_stream (GstCaps * parent, GstCaps * child) return TRUE; } + if (is_subtitle_caps (parent)) + return TRUE; + return FALSE; } @@ -970,7 +1025,7 @@ discoverer_collect (GstDiscoverer * dc) * caps named image/<foo> (th exception being MJPEG video which is also * type image/jpeg), and should consist of precisely one stream (actually * initially there are 2, the image and raw stream, but we squash these - * while parsing the stream topology). At some ponit, if we find that these + * while parsing the stream topology). At some point, if we find that these * conditions are not sufficient, we can count the number of decoders and * parsers in the chain, and if there's more than one decoder, or any * parser at all, we should not mark this as an image. diff --git a/gst-libs/gst/pbutils/gstdiscoverer.h b/gst-libs/gst/pbutils/gstdiscoverer.h index 5225738f6..2b833aae2 100644 --- a/gst-libs/gst/pbutils/gstdiscoverer.h +++ b/gst-libs/gst/pbutils/gstdiscoverer.h @@ -110,6 +110,7 @@ guint gst_discoverer_audio_info_get_sample_rate(const GstDiscovererAudioInfo* in guint gst_discoverer_audio_info_get_depth(const GstDiscovererAudioInfo* info); guint gst_discoverer_audio_info_get_bitrate(const GstDiscovererAudioInfo* info); guint gst_discoverer_audio_info_get_max_bitrate(const GstDiscovererAudioInfo* info); +const gchar * gst_discoverer_audio_info_get_language(const GstDiscovererAudioInfo* info); /** * GstDiscovererVideoInfo: @@ -141,6 +142,26 @@ guint gst_discoverer_video_info_get_max_bitrate(const GstDiscovererVid gboolean gst_discoverer_video_info_is_image(const GstDiscovererVideoInfo* info); /** + * GstDiscovererSubtitleInfo: + * + * #GstDiscovererStreamInfo specific to subtitle streams (this includes text and + * image based ones). + * + * Since: 0.10.36 + */ +#define GST_TYPE_DISCOVERER_SUBTITLE_INFO \ + (gst_discoverer_subtitle_info_get_type ()) +#define GST_DISCOVERER_SUBTITLE_INFO(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_DISCOVERER_SUBTITLE_INFO, GstDiscovererSubtitleInfo)) +#define GST_IS_DISCOVERER_SUBTITLE_INFO(obj) \ + (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_DISCOVERER_SUBTITLE_INFO)) +typedef struct _GstDiscovererSubtitleInfo GstDiscovererSubtitleInfo; +typedef GstMiniObjectClass GstDiscovererSubtitleInfoClass; +GType gst_discoverer_subtitle_info_get_type (void); + +const gchar * gst_discoverer_subtitle_info_get_language(const GstDiscovererSubtitleInfo* info); + +/** * GstDiscovererResult: * @GST_DISCOVERER_OK: The discovery was successful * @GST_DISCOVERER_URI_INVALID: the URI is invalid @@ -199,6 +220,7 @@ GList * gst_discoverer_info_get_streams (GstDiscovererInfo *in GType streamtype); GList * gst_discoverer_info_get_audio_streams (GstDiscovererInfo *info); GList * gst_discoverer_info_get_video_streams (GstDiscovererInfo *info); +GList * gst_discoverer_info_get_subtitle_streams (GstDiscovererInfo *info); GList * gst_discoverer_info_get_container_streams (GstDiscovererInfo *info); void gst_discoverer_stream_info_list_free (GList *infos); diff --git a/gst-libs/gst/pbutils/pbutils-private.h b/gst-libs/gst/pbutils/pbutils-private.h index 2d7fcd8d9..8ac614791 100644 --- a/gst-libs/gst/pbutils/pbutils-private.h +++ b/gst-libs/gst/pbutils/pbutils-private.h @@ -44,6 +44,8 @@ struct _GstDiscovererAudioInfo { guint bitrate; guint max_bitrate; + + gchar *language; }; struct _GstDiscovererVideoInfo { @@ -64,6 +66,12 @@ struct _GstDiscovererVideoInfo { gboolean is_image; }; +struct _GstDiscovererSubtitleInfo { + GstDiscovererStreamInfo parent; + + gchar *language; +}; + struct _GstDiscovererInfo { GObject parent; diff --git a/gst-libs/gst/rtp/gstbasertppayload.c b/gst-libs/gst/rtp/gstbasertppayload.c index 112f9a424..3bca8525e 100644 --- a/gst-libs/gst/rtp/gstbasertppayload.c +++ b/gst-libs/gst/rtp/gstbasertppayload.c @@ -20,7 +20,7 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" +#include "config.h" #endif #include <string.h> @@ -44,6 +44,9 @@ struct _GstBaseRTPPayloadPrivate gboolean perfect_rtptime; gint notified_first_timestamp; + guint64 base_offset; + gint64 base_rtime; + gint64 prop_max_ptime; gint64 caps_max_ptime; }; @@ -293,6 +296,8 @@ gst_basertppayload_init (GstBaseRTPPayload * basertppayload, gpointer g_class) basertppayload->min_ptime = DEFAULT_MIN_PTIME; basertppayload->priv->perfect_rtptime = DEFAULT_PERFECT_RTPTIME; basertppayload->abidata.ABI.ptime_multiple = DEFAULT_PTIME_MULTIPLE; + basertppayload->priv->base_offset = GST_BUFFER_OFFSET_NONE; + basertppayload->priv->base_rtime = GST_BUFFER_OFFSET_NONE; basertppayload->media = NULL; basertppayload->encoding_name = NULL; @@ -393,6 +398,8 @@ gst_basertppayload_event_default (GstBaseRTPPayload * basertppayload, segment = &basertppayload->segment; gst_event_copy_segment (event, segment); + basertppayload->priv->base_offset = GST_BUFFER_OFFSET_NONE; + GST_DEBUG_OBJECT (basertppayload, "configured SEGMENT %" GST_SEGMENT_FORMAT, segment); res = gst_pad_event_default (basertppayload->sinkpad, event); @@ -772,9 +779,11 @@ gst_basertppayload_prepare_push (GstBaseRTPPayload * payload, } /* convert to RTP time */ - if (priv->perfect_rtptime && data.offset != GST_BUFFER_OFFSET_NONE) { + if (priv->perfect_rtptime && data.offset != GST_BUFFER_OFFSET_NONE && + priv->base_offset != GST_BUFFER_OFFSET_NONE) { /* if we have an offset, use that for making an RTP timestamp */ - data.rtptime = payload->ts_base + data.offset; + data.rtptime = payload->ts_base + priv->base_rtime + + data.offset - priv->base_offset; GST_LOG_OBJECT (payload, "Using offset %" G_GUINT64_FORMAT " for RTP timestamp", data.offset); } else if (GST_CLOCK_TIME_IS_VALID (data.timestamp)) { @@ -793,6 +802,8 @@ gst_basertppayload_prepare_push (GstBaseRTPPayload * payload, GST_TIME_ARGS (rtime)); rtime = gst_util_uint64_scale_int (rtime, payload->clock_rate, GST_SECOND); + priv->base_offset = data.offset; + priv->base_rtime = rtime; } /* add running_time in clock-rate units to the base timestamp */ data.rtptime = payload->ts_base + rtime; @@ -1041,6 +1052,7 @@ gst_basertppayload_change_state (GstElement * element, basertppayload->ts_base = basertppayload->ts_offset; basertppayload->timestamp = basertppayload->ts_base; g_atomic_int_set (&basertppayload->priv->notified_first_timestamp, 1); + priv->base_offset = GST_BUFFER_OFFSET_NONE; break; default: break; diff --git a/gst/playback/gstplaysink.c b/gst/playback/gstplaysink.c index e0a540b76..f95e3e951 100644 --- a/gst/playback/gstplaysink.c +++ b/gst/playback/gstplaysink.c @@ -1262,9 +1262,9 @@ gen_video_chain (GstPlaySink * playsink, gboolean raw, gboolean async) } /* find ts-offset element */ - chain->ts_offset = + gst_object_replace ((GstObject **) & chain->ts_offset, (GstObject *) gst_play_sink_find_property_sinks (playsink, chain->sink, "ts-offset", - G_TYPE_INT64); + G_TYPE_INT64)); /* create a bin to hold objects, as we create them we add them to this bin so * that when something goes wrong we only need to unref the bin */ @@ -1387,9 +1387,10 @@ setup_video_chain (GstPlaySink * playsink, gboolean raw, gboolean async) return FALSE; /* find ts-offset element */ - chain->ts_offset = + + gst_object_replace ((GstObject **) & chain->ts_offset, (GstObject *) gst_play_sink_find_property_sinks (playsink, chain->sink, "ts-offset", - G_TYPE_INT64); + G_TYPE_INT64)); /* if we can disable async behaviour of the sink, we can avoid adding a * queue for the audio chain. */ @@ -1704,9 +1705,9 @@ gen_audio_chain (GstPlaySink * playsink, gboolean raw) } /* find ts-offset element */ - chain->ts_offset = + gst_object_replace ((GstObject **) & chain->ts_offset, (GstObject *) gst_play_sink_find_property_sinks (playsink, chain->sink, "ts-offset", - G_TYPE_INT64); + G_TYPE_INT64)); /* check if the sink, or something within the sink, has the volume property. * If it does we don't need to add a volume element. */ @@ -1887,9 +1888,9 @@ setup_audio_chain (GstPlaySink * playsink, gboolean raw) return FALSE; /* find ts-offset element */ - chain->ts_offset = + gst_object_replace ((GstObject **) & chain->ts_offset, (GstObject *) gst_play_sink_find_property_sinks (playsink, chain->sink, "ts-offset", - G_TYPE_INT64); + G_TYPE_INT64)); /* check if the sink, or something within the sink, has the volume property. * If it does we don't need to add a volume element. */ @@ -2303,6 +2304,7 @@ gst_play_sink_reconfigure (GstPlaySink * playsink) add_chain (GST_PLAY_CHAIN (playsink->videochain), FALSE); activate_chain (GST_PLAY_CHAIN (playsink->videochain), FALSE); + g_object_unref (playsink->videochain->ts_offset); playsink->videochain->ts_offset = NULL; } @@ -2356,6 +2358,7 @@ gst_play_sink_reconfigure (GstPlaySink * playsink) disconnect_chain (playsink->audiochain, playsink); playsink->audiochain->volume = NULL; playsink->audiochain->mute = NULL; + g_object_unref (playsink->audiochain->ts_offset); playsink->audiochain->ts_offset = NULL; free_chain ((GstPlayChain *) playsink->audiochain); playsink->audiochain = NULL; @@ -2426,6 +2429,7 @@ gst_play_sink_reconfigure (GstPlaySink * playsink) disconnect_chain (playsink->audiochain, playsink); playsink->audiochain->volume = NULL; playsink->audiochain->mute = NULL; + g_object_unref (playsink->audiochain->ts_offset); playsink->audiochain->ts_offset = NULL; } add_chain (GST_PLAY_CHAIN (playsink->audiochain), FALSE); @@ -3020,14 +3024,14 @@ caps_notify_cb (GstPad * pad, GParamSpec * unused, GstPlaySink * playsink) if (pad == playsink->audio_pad) { raw = is_raw_pad (pad); - reconfigure = (! !playsink->audio_pad_raw != ! !raw) + reconfigure = (!!playsink->audio_pad_raw != !!raw) && playsink->audiochain; GST_DEBUG_OBJECT (pad, "Audio caps changed: raw %d reconfigure %d caps %" GST_PTR_FORMAT, raw, reconfigure, caps); } else if (pad == playsink->video_pad) { raw = is_raw_pad (pad); - reconfigure = (! !playsink->video_pad_raw != ! !raw) + reconfigure = (!!playsink->video_pad_raw != !!raw) && playsink->videochain; GST_DEBUG_OBJECT (pad, "Video caps changed: raw %d reconfigure %d caps %" GST_PTR_FORMAT, raw, @@ -3418,6 +3422,7 @@ gst_play_sink_change_state (GstElement * element, GstStateChange transition) disconnect_chain (playsink->audiochain, playsink); playsink->audiochain->volume = NULL; playsink->audiochain->mute = NULL; + g_object_unref (playsink->audiochain->ts_offset); playsink->audiochain->ts_offset = NULL; } ret = GST_STATE_CHANGE_SUCCESS; diff --git a/gst/playback/gstplaysinkaudioconvert.c b/gst/playback/gstplaysinkaudioconvert.c index 08f356e04..c409d025c 100644 --- a/gst/playback/gstplaysinkaudioconvert.c +++ b/gst/playback/gstplaysinkaudioconvert.c @@ -72,6 +72,28 @@ post_missing_element_message (GstPlaySinkAudioConvert * self, gst_element_post_message (GST_ELEMENT_CAST (self), msg); } +static void +distribute_running_time (GstElement * element, const GstSegment * segment) +{ + GstEvent *event; + GstPad *pad; + + pad = gst_element_get_static_pad (element, "sink"); + + if (segment->accum) { + event = gst_event_new_new_segment_full (FALSE, segment->rate, + segment->applied_rate, segment->format, 0, segment->accum, 0); + gst_pad_send_event (pad, event); + } + + event = gst_event_new_new_segment_full (FALSE, segment->rate, + segment->applied_rate, segment->format, + segment->start, segment->stop, segment->time); + gst_pad_send_event (pad, event); + + gst_object_unref (pad); +} + static GstProbeReturn pad_blocked_cb (GstPad * pad, GstProbeType type, gpointer type_data, gpointer user_data) diff --git a/gst/playback/gstplaysinkvideoconvert.c b/gst/playback/gstplaysinkvideoconvert.c index 494d44abd..a8c710d1b 100644 --- a/gst/playback/gstplaysinkvideoconvert.c +++ b/gst/playback/gstplaysinkvideoconvert.c @@ -72,6 +72,28 @@ post_missing_element_message (GstPlaySinkVideoConvert * self, gst_element_post_message (GST_ELEMENT_CAST (self), msg); } +static void +distribute_running_time (GstElement * element, const GstSegment * segment) +{ + GstEvent *event; + GstPad *pad; + + pad = gst_element_get_static_pad (element, "sink"); + + if (segment->accum) { + event = gst_event_new_new_segment_full (FALSE, segment->rate, + segment->applied_rate, segment->format, 0, segment->accum, 0); + gst_pad_send_event (pad, event); + } + + event = gst_event_new_new_segment_full (FALSE, segment->rate, + segment->applied_rate, segment->format, + segment->start, segment->stop, segment->time); + gst_pad_send_event (pad, event); + + gst_object_unref (pad); +} + static GstProbeReturn pad_blocked_cb (GstPad * pad, GstProbeType type, gpointer type_data, gpointer user_data) diff --git a/tools/gst-discoverer.c b/tools/gst-discoverer.c index bcadc1b91..5b2a74be4 100644 --- a/tools/gst-discoverer.c +++ b/tools/gst-discoverer.c @@ -47,6 +47,7 @@ gst_stream_audio_information_to_string (GstDiscovererStreamInfo * info, GstDiscovererAudioInfo *audio_info; GString *s; gchar *tmp; + const gchar *ctmp; int len = 400; const GstTagList *tags; GstCaps *caps; @@ -72,6 +73,8 @@ gst_stream_audio_information_to_string (GstDiscovererStreamInfo * info, } audio_info = (GstDiscovererAudioInfo *) info; + ctmp = gst_discoverer_audio_info_get_language (audio_info); + my_g_string_append_printf (s, "Language: %s\n", ctmp ? ctmp : "<unknown>"); my_g_string_append_printf (s, "Channels: %u\n", gst_discoverer_audio_info_get_channels (audio_info)); my_g_string_append_printf (s, "Sample rate: %u\n", @@ -171,6 +174,57 @@ gst_stream_video_information_to_string (GstDiscovererStreamInfo * info, return g_string_free (s, FALSE); } +static gchar * +gst_stream_subtitle_information_to_string (GstDiscovererStreamInfo * info, + gint depth) +{ + GstDiscovererSubtitleInfo *subtitle_info; + GString *s; + gchar *tmp; + const gchar *ctmp; + int len = 400; + const GstTagList *tags; + GstCaps *caps; + + g_return_val_if_fail (info != NULL, NULL); + + s = g_string_sized_new (len); + + my_g_string_append_printf (s, "Codec:\n"); + caps = gst_discoverer_stream_info_get_caps (info); + tmp = gst_caps_to_string (caps); + gst_caps_unref (caps); + my_g_string_append_printf (s, " %s\n", tmp); + g_free (tmp); + + my_g_string_append_printf (s, "Additional info:\n"); + if (gst_discoverer_stream_info_get_misc (info)) { + tmp = gst_structure_to_string (gst_discoverer_stream_info_get_misc (info)); + my_g_string_append_printf (s, " %s\n", tmp); + g_free (tmp); + } else { + my_g_string_append_printf (s, " None\n"); + } + + subtitle_info = (GstDiscovererSubtitleInfo *) info; + ctmp = gst_discoverer_subtitle_info_get_language (subtitle_info); + my_g_string_append_printf (s, "Language: %s\n", ctmp ? ctmp : "<unknown>"); + + my_g_string_append_printf (s, "Tags:\n"); + tags = gst_discoverer_stream_info_get_tags (info); + if (tags) { + tmp = gst_structure_to_string ((GstStructure *) tags); + my_g_string_append_printf (s, " %s\n", tmp); + g_free (tmp); + } else { + my_g_string_append_printf (s, " None\n"); + } + if (verbose) + my_g_string_append_printf (s, "\n"); + + return g_string_free (s, FALSE); +} + static void print_stream_info (GstDiscovererStreamInfo * info, void *depth) { @@ -204,6 +258,10 @@ print_stream_info (GstDiscovererStreamInfo * info, void *depth) desc = gst_stream_video_information_to_string (info, GPOINTER_TO_INT (depth) + 1); + else if (GST_IS_DISCOVERER_SUBTITLE_INFO (info)) + desc = + gst_stream_subtitle_information_to_string (info, + GPOINTER_TO_INT (depth) + 1); if (desc) { g_print ("%s", desc); g_free (desc); diff --git a/win32/common/libgstaudio.def b/win32/common/libgstaudio.def index 1e2fff447..568f03310 100644 --- a/win32/common/libgstaudio.def +++ b/win32/common/libgstaudio.def @@ -1,4 +1,5 @@ EXPORTS + _gst_base_audio_decoder_error gst_audio_buffer_clip gst_audio_channel_position_get_type gst_audio_check_channel_positions @@ -31,6 +32,47 @@ EXPORTS gst_audio_set_structure_channel_positions_list gst_audio_sink_get_type gst_audio_src_get_type + gst_audio_structure_set_int + gst_base_audio_decoder_finish_frame + gst_base_audio_decoder_get_audio_info + gst_base_audio_decoder_get_byte_time + gst_base_audio_decoder_get_delay + gst_base_audio_decoder_get_latency + gst_base_audio_decoder_get_max_errors + gst_base_audio_decoder_get_min_latency + gst_base_audio_decoder_get_parse_state + gst_base_audio_decoder_get_plc + gst_base_audio_decoder_get_plc_aware + gst_base_audio_decoder_get_tolerance + gst_base_audio_decoder_get_type + gst_base_audio_decoder_set_byte_time + gst_base_audio_decoder_set_latency + gst_base_audio_decoder_set_max_errors + gst_base_audio_decoder_set_min_latency + gst_base_audio_decoder_set_plc + gst_base_audio_decoder_set_plc_aware + gst_base_audio_decoder_set_tolerance + gst_base_audio_encoder_finish_frame + gst_base_audio_encoder_get_audio_info + gst_base_audio_encoder_get_frame_max + gst_base_audio_encoder_get_frame_samples + gst_base_audio_encoder_get_hard_resync + gst_base_audio_encoder_get_latency + gst_base_audio_encoder_get_lookahead + gst_base_audio_encoder_get_mark_granule + gst_base_audio_encoder_get_perfect_timestamp + gst_base_audio_encoder_get_tolerance + gst_base_audio_encoder_get_type + gst_base_audio_encoder_proxy_getcaps + gst_base_audio_encoder_set_frame_max + gst_base_audio_encoder_set_frame_samples + gst_base_audio_encoder_set_hard_resync + gst_base_audio_encoder_set_latency + gst_base_audio_encoder_set_lookahead + gst_base_audio_encoder_set_mark_granule + gst_base_audio_encoder_set_perfect_timestamp + gst_base_audio_encoder_set_tolerance +>>>>>>> master gst_base_audio_sink_create_ringbuffer gst_base_audio_sink_get_drift_tolerance gst_base_audio_sink_get_provide_clock diff --git a/win32/common/libgstpbutils.def b/win32/common/libgstpbutils.def index c07e39002..3fa74d44b 100644 --- a/win32/common/libgstpbutils.def +++ b/win32/common/libgstpbutils.def @@ -13,6 +13,7 @@ EXPORTS gst_discoverer_audio_info_get_bitrate gst_discoverer_audio_info_get_channels gst_discoverer_audio_info_get_depth + gst_discoverer_audio_info_get_language gst_discoverer_audio_info_get_max_bitrate gst_discoverer_audio_info_get_sample_rate gst_discoverer_audio_info_get_type @@ -31,6 +32,7 @@ EXPORTS gst_discoverer_info_get_stream_info gst_discoverer_info_get_stream_list gst_discoverer_info_get_streams + gst_discoverer_info_get_subtitle_streams gst_discoverer_info_get_tags gst_discoverer_info_get_type gst_discoverer_info_get_uri @@ -47,6 +49,8 @@ EXPORTS gst_discoverer_stream_info_get_tags gst_discoverer_stream_info_get_type gst_discoverer_stream_info_list_free + gst_discoverer_subtitle_info_get_language + gst_discoverer_subtitle_info_get_type gst_discoverer_video_info_get_bitrate gst_discoverer_video_info_get_depth gst_discoverer_video_info_get_framerate_denom |