baesparse: fix refactor regression in loop based parsing
[platform/upstream/gstreamer.git] / gst / audioparsers / gstbaseparse.c
index bc50a9c..63ac08d 100644 (file)
@@ -76,7 +76,7 @@
  *       #GstAdapter.
  *     </para></listitem>
  *     <listitem><para>
- *       A buffer of min_frame_size bytes is passed to subclass with
+ *       A buffer of (at least) min_frame_size bytes is passed to subclass with
  *       @check_valid_frame. Subclass checks the contents and returns TRUE
  *       if the buffer contains a valid frame. It also needs to set the
  *       @framesize according to the detected frame size. If buffer didn't
  *     <listitem><para>
  *       After valid frame is found, it will be passed again to subclass with
  *       @parse_frame call. Now subclass is responsible for parsing the
- *       frame contents and setting the buffer timestamp, duration and caps.
+ *       frame contents and setting the caps, buffer timestamp and duration
+ *       (although the latter can also be done by GstBaseParse if it is
+ *       appropriately configured, see below).
  *     </para></listitem>
  *     <listitem><para>
  *       Finally the buffer can be pushed downstream and parsing loop starts
- *       over again.
+ *       over again.  Just prior to actually pushing the buffer in question,
+ *       it is passed to @pre_push_buffer which gives subclass yet one
+ *       last chance to examine buffer metadata, or to send some custom (tag)
+ *       events, or to perform custom (segment) filtering.
  *     </para></listitem>
  *     <listitem><para>
  *       During the parsing process GstBaseParseClass will handle both srcpad and
  * GST_FORMAT_TIME to GST_FORMAT_DEFAULT must return the
  * frame number that can be found from the given byte position.
  *
- * GstBaseParse uses subclasses conversion methods also for seeking. If
- * subclass doesn't provide @convert function, seeking will get disabled.
+ * GstBaseParse uses subclasses conversion methods also for seeking (or otherwise
+ * uses its own default one, see also below).
  *
  * Subclass @start and @stop functions will be called to inform the beginning
  * and end of data processing.
  *      Update the duration information with @gst_base_parse_set_duration
  *   </para></listitem>
  *   <listitem><para>
- *      Alternatively, parsing (or specs) might yield a frames per seconds rate
- *      which can be provided to GstBaseParse to enable it to cater for
+ *      Optionally passthrough using @gst_base_parse_set_passthrough
+ *   </para></listitem>
+ *   <listitem><para>
+ *      Configure various baseparse parameters using @gst_base_parse_set_seek and
+ *      @gst_base_parse_set_frame_props.
+ *   </para></listitem>
+ *   <listitem><para>
+ *      In particular, if subclass is unable to determine a duration, but
+ *      parsing (or specs) yields a frames per seconds rate, then this can be
+ *      provided to GstBaseParse to enable it to cater for
  *      buffer time metadata (which will be taken from upstream as much as possible).
- *      Internally keeping track of frames and respective
- *      sizes that have been pushed provides GstBaseParse with a bytes per frame
- *      rate.  A default @convert (used if not overriden) will then use these
+ *      Internally keeping track of frame durations and respective
+ *      sizes that have been pushed provides GstBaseParse with an estimated bitrate.
+ *      A default @convert (used if not overriden) will then use these
  *      rates to perform obvious conversions.  These rates are also used to update
  *      (estimated) duration at regular frame intervals.
- *      If no (fixed) frames per second rate applies, default conversion will be
- *      based on (estimated) bytes per second (but no default buffer metadata
- *      can be provided in this case).
  *   </para></listitem>
  * </itemizedlist>
  *
  */
 
 /* TODO:
- *  - Better segment handling:
- *    - NEWSEGMENT for gaps
- *    - Not NEWSEGMENT starting at 0 but at first frame timestamp
- *  - GstIndex support
- *  - Seek table generation and subclass seek entry injection
- *  - Accurate seeking
  *  - In push mode provide a queue of adapter-"queued" buffers for upstream
  *    buffer metadata
  *  - Queue buffers/events until caps are set
- *  - Let subclass decide if frames outside the segment should be dropped
- *  - Send queries upstream
  */
 
 #ifdef HAVE_CONFIG_H
 #include "gstbaseparse.h"
 
 #define MIN_FRAMES_TO_POST_BITRATE 10
+#define TARGET_DIFFERENCE          (20 * GST_SECOND)
 
 GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
 #define GST_CAT_DEFAULT gst_base_parse_debug
@@ -219,6 +222,8 @@ struct _GstBaseParsePrivate
   guint fps_num, fps_den;
   guint update_interval;
   guint bitrate;
+  guint lead_in, lead_out;
+  GstClockTime lead_in_ts, lead_out_ts;
   GstBaseParseSeekable seekable;
 
   gboolean discont;
@@ -230,11 +235,15 @@ struct _GstBaseParsePrivate
   GstClockTime next_ts;
   GstClockTime prev_ts;
   GstClockTime frame_duration;
+  gboolean seen_keyframe;
+  gboolean is_video;
 
   guint64 framecount;
   guint64 bytecount;
   guint64 data_bytecount;
   guint64 acc_duration;
+  GstClockTime first_frame_ts;
+  gint64 first_frame_offset;
 
   gboolean post_min_bitrate;
   gboolean post_avg_bitrate;
@@ -254,13 +263,35 @@ struct _GstBaseParsePrivate
   gboolean own_index;
   /* seek table entries only maintained if upstream is BYTE seekable */
   gboolean upstream_seekable;
+  gboolean upstream_has_duration;
+  gint64 upstream_size;
   /* minimum distance between two index entries */
   GstClockTimeDiff idx_interval;
   /* ts and offset of last entry added */
   GstClockTime index_last_ts;
   guint64 index_last_offset;
+  gboolean index_last_valid;
+
+  /* timestamps currently produced are accurate, e.g. started from 0 onwards */
+  gboolean exact_position;
+  /* seek events are temporarily kept to match them with newsegments */
+  GSList *pending_seeks;
+
+  /* reverse playback */
+  GSList *buffers_pending;
+  GSList *buffers_queued;
+  GstClockTime last_ts;
+  gint64 last_offset;
 };
 
+typedef struct _GstBaseParseSeek
+{
+  GstSegment segment;
+  gboolean accurate;
+  gint64 offset;
+  GstClockTime start_ts;
+} GstBaseParseSeek;
+
 static GstElementClass *parent_class = NULL;
 
 static void gst_base_parse_class_init (GstBaseParseClass * klass);
@@ -335,13 +366,32 @@ static void gst_base_parse_drain (GstBaseParse * parse);
 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
     gboolean post_min, gboolean post_avg, gboolean post_max);
 
+static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
+    GstClockTime time, gboolean before, GstClockTime * _ts);
+static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
+    GstClockTime * _time, gint64 * _offset);
+
+static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
+    gboolean push_only);
+
+static void
+gst_base_parse_clear_queues (GstBaseParse * parse)
+{
+  g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
+  g_slist_free (parse->priv->buffers_queued);
+  parse->priv->buffers_queued = NULL;
+  g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
+      NULL);
+  g_slist_free (parse->priv->buffers_pending);
+  parse->priv->buffers_pending = NULL;
+}
+
 static void
 gst_base_parse_finalize (GObject * object)
 {
   GstBaseParse *parse = GST_BASE_PARSE (object);
   GstEvent **p_ev;
 
-  g_mutex_free (parse->parse_lock);
   g_object_unref (parse->adapter);
 
   if (parse->pending_segment) {
@@ -368,6 +418,8 @@ gst_base_parse_finalize (GObject * object)
     parse->priv->index = NULL;
   }
 
+  gst_base_parse_clear_queues (parse);
+
   G_OBJECT_CLASS (parent_class)->finalize (object);
 }
 
@@ -441,7 +493,6 @@ gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
   gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
   GST_DEBUG_OBJECT (parse, "src created");
 
-  parse->parse_lock = g_mutex_new ();
   parse->adapter = gst_adapter_new ();
 
   parse->priv->pad_mode = GST_ACTIVATE_NONE;
@@ -465,11 +516,15 @@ gst_base_parse_reset (GstBaseParse * parse)
   parse->priv->update_interval = 50;
   parse->priv->fps_num = parse->priv->fps_den = 0;
   parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
+  parse->priv->lead_in = parse->priv->lead_out = 0;
+  parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
   parse->priv->seekable = GST_BASE_PARSE_SEEK_DEFAULT;
   parse->priv->bitrate = 0;
   parse->priv->framecount = 0;
   parse->priv->bytecount = 0;
   parse->priv->acc_duration = 0;
+  parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
+  parse->priv->first_frame_offset = -1;
   parse->priv->estimated_duration = -1;
   parse->priv->next_ts = 0;
   parse->priv->passthrough = FALSE;
@@ -483,11 +538,21 @@ gst_base_parse_reset (GstBaseParse * parse)
 
   parse->priv->index_last_ts = 0;
   parse->priv->index_last_offset = 0;
+  parse->priv->index_last_valid = TRUE;
   parse->priv->upstream_seekable = FALSE;
+  parse->priv->upstream_size = 0;
+  parse->priv->upstream_has_duration = FALSE;
   parse->priv->idx_interval = 0;
+  parse->priv->exact_position = TRUE;
+  parse->priv->seen_keyframe = FALSE;
 
-  if (parse->pending_segment)
+  parse->priv->last_ts = GST_CLOCK_TIME_NONE;
+  parse->priv->last_offset = 0;
+
+  if (parse->pending_segment) {
     gst_event_unref (parse->pending_segment);
+    parse->pending_segment = NULL;
+  }
 
   g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
       NULL);
@@ -498,6 +563,11 @@ gst_base_parse_reset (GstBaseParse * parse)
     gst_buffer_unref (parse->priv->cache);
     parse->priv->cache = NULL;
   }
+
+  g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
+  g_slist_free (parse->priv->pending_seeks);
+  parse->priv->pending_seeks = NULL;
+
   GST_OBJECT_UNLOCK (parse);
 }
 
@@ -616,11 +686,11 @@ gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
   gboolean handled = FALSE;
   gboolean ret = TRUE;
 
-
   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
   bclass = GST_BASE_PARSE_GET_CLASS (parse);
 
-  GST_DEBUG_OBJECT (parse, "handling event %d", GST_EVENT_TYPE (event));
+  GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
+      GST_EVENT_TYPE_NAME (event));
 
   /* Cache all events except EOS, NEWSEGMENT and FLUSH_STOP if we have a
    * pending segment */
@@ -666,7 +736,10 @@ gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
  *
  * Element-level event handler function.
  *
- * Returns: TRUE if the event was handled and not need forwarding.
+ * The event will be unreffed only if it has been handled and this
+ * function returns %TRUE
+ *
+ * Returns: %TRUE if the event was handled and not need forwarding.
  */
 static gboolean
 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
@@ -679,57 +752,86 @@ gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
     {
       gdouble rate, applied_rate;
       GstFormat format;
-      gint64 start, stop, pos, offset = 0;
+      gint64 start, stop, pos, next_ts, offset = 0;
       gboolean update;
 
       gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
           &format, &start, &stop, &pos);
 
+      GST_DEBUG_OBJECT (parse, "newseg rate %g, applied rate %g, "
+          "format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
+          ", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
+          GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
 
       if (format == GST_FORMAT_BYTES) {
-        GstClockTime seg_start, seg_stop, seg_pos;
+        GstClockTime seg_start, seg_stop;
+        GstBaseParseSeek *seek = NULL;
+        GSList *node;
 
         /* stop time is allowed to be open-ended, but not start & pos */
         seg_stop = GST_CLOCK_TIME_NONE;
+        seg_start = 0;
         offset = pos;
 
-        if (gst_base_parse_convert (parse, GST_FORMAT_BYTES, start,
-                GST_FORMAT_TIME, (gint64 *) & seg_start) &&
-            gst_base_parse_convert (parse, GST_FORMAT_BYTES, pos,
-                GST_FORMAT_TIME, (gint64 *) & seg_pos)) {
-          gst_event_unref (event);
-          event = gst_event_new_new_segment_full (update, rate, applied_rate,
-              GST_FORMAT_TIME, seg_start, seg_stop, seg_pos);
-          format = GST_FORMAT_TIME;
-          GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
-              "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
-              ", pos = %" GST_TIME_FORMAT, GST_TIME_ARGS (seg_start),
-              GST_TIME_ARGS (seg_stop), GST_TIME_ARGS (seg_pos));
+        GST_OBJECT_LOCK (parse);
+        for (node = parse->priv->pending_seeks; node; node = node->next) {
+          GstBaseParseSeek *tmp = node->data;
+
+          if (tmp->offset == pos) {
+            seek = tmp;
+            break;
+          }
         }
-      }
+        parse->priv->pending_seeks =
+            g_slist_remove (parse->priv->pending_seeks, seek);
+        GST_OBJECT_UNLOCK (parse);
 
-      if (format != GST_FORMAT_TIME) {
+        if (seek) {
+          GST_DEBUG_OBJECT (parse,
+              "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
+              seek->accurate ? " accurate" : "", &seek->segment);
+          seg_start = seek->segment.start;
+          seg_stop = seek->segment.stop;
+          next_ts = seek->start_ts;
+          parse->priv->exact_position = seek->accurate;
+          g_free (seek);
+        } else {
+          /* best attempt convert */
+          /* as these are only estimates, stop is kept open-ended to avoid
+           * premature cutting */
+          gst_base_parse_convert (parse, GST_FORMAT_BYTES, start,
+              GST_FORMAT_TIME, (gint64 *) & seg_start);
+          parse->priv->exact_position = (start == 0);
+          next_ts = seg_start;
+        }
+
+        gst_event_unref (event);
+        event = gst_event_new_new_segment_full (update, rate, applied_rate,
+            GST_FORMAT_TIME, seg_start, seg_stop, seg_start);
+        format = GST_FORMAT_TIME;
+        start = seg_start;
+        stop = seg_stop;
+        GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
+            "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT,
+            GST_TIME_ARGS (seg_start), GST_TIME_ARGS (seg_stop));
+      } else if (format != GST_FORMAT_TIME) {
         /* Unknown incoming segment format. Output a default open-ended 
          * TIME segment */
         gst_event_unref (event);
         event = gst_event_new_new_segment_full (update, rate, applied_rate,
             GST_FORMAT_TIME, 0, GST_CLOCK_TIME_NONE, 0);
+        format = GST_FORMAT_TIME;
+        next_ts = start = 0;
+        stop = GST_CLOCK_TIME_NONE;
       } else {
         /* not considered BYTE seekable if it is talking to us in TIME,
          * whatever else it might claim */
         parse->priv->upstream_seekable = FALSE;
+        next_ts = start;
       }
 
-      gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
-          &format, &start, &stop, &pos);
-
       gst_segment_set_newsegment_full (&parse->segment, update, rate,
-          applied_rate, format, start, stop, pos);
-
-      GST_DEBUG_OBJECT (parse, "Created newseg rate %g, applied rate %g, "
-          "format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
-          ", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
-          GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
+          applied_rate, format, start, stop, start);
 
       /* save the segment for later, right before we push a new buffer so that
        * the caps are fixed and the next linked element can receive
@@ -741,18 +843,25 @@ gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
 
       /* but finish the current segment */
       GST_DEBUG_OBJECT (parse, "draining current segment");
-      gst_base_parse_drain (parse);
+      if (parse->segment.rate > 0.0)
+        gst_base_parse_drain (parse);
+      else
+        gst_base_parse_process_fragment (parse, FALSE);
       gst_adapter_clear (parse->adapter);
       parse->priv->offset = offset;
       parse->priv->sync_offset = offset;
-      parse->priv->next_ts = start;
+      parse->priv->next_ts = next_ts;
+      parse->priv->last_ts = GST_CLOCK_TIME_NONE;
       parse->priv->discont = TRUE;
+      parse->priv->seen_keyframe = FALSE;
       break;
     }
 
     case GST_EVENT_FLUSH_START:
       parse->priv->flushing = TRUE;
-      handled = gst_pad_push_event (parse->srcpad, event);
+      handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
+      if (handled)
+        gst_event_unref (event);
       /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
       GST_PAD_STREAM_LOCK (parse->srcpad);
       GST_PAD_STREAM_UNLOCK (parse->srcpad);
@@ -761,12 +870,17 @@ gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
 
     case GST_EVENT_FLUSH_STOP:
       gst_adapter_clear (parse->adapter);
+      gst_base_parse_clear_queues (parse);
       parse->priv->flushing = FALSE;
       parse->priv->discont = TRUE;
+      parse->priv->last_ts = GST_CLOCK_TIME_NONE;
       break;
 
     case GST_EVENT_EOS:
-      gst_base_parse_drain (parse);
+      if (parse->segment.rate > 0.0)
+        gst_base_parse_drain (parse);
+      else
+        gst_base_parse_process_fragment (parse, FALSE);
 
       /* If we STILL have zero frames processed, fire an error */
       if (parse->priv->framecount == 0) {
@@ -837,9 +951,6 @@ static gboolean
 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
 {
   gboolean handled = FALSE;
-  GstBaseParseClass *bclass;
-
-  bclass = GST_BASE_PARSE_GET_CLASS (parse);
 
   switch (GST_EVENT_TYPE (event)) {
     case GST_EVENT_SEEK:
@@ -895,14 +1006,8 @@ gst_base_parse_convert_default (GstBaseParse * parse,
   if (!parse->priv->framecount)
     return FALSE;
 
-  /* either frame info (having num means den also ok) or use average bitrate */
-  if (parse->priv->fps_num) {
-    duration = parse->priv->framecount * parse->priv->fps_den * 1000;
-    bytes = parse->priv->bytecount * parse->priv->fps_num;
-  } else {
-    duration = parse->priv->acc_duration / GST_MSECOND;
-    bytes = parse->priv->bytecount;
-  }
+  duration = parse->priv->acc_duration / GST_MSECOND;
+  bytes = parse->priv->bytecount;
 
   if (G_UNLIKELY (!duration || !bytes))
     return FALSE;
@@ -1028,13 +1133,9 @@ gst_base_parse_update_bitrates (GstBaseParse * parse, GstBuffer * buffer)
   data_len = GST_BUFFER_SIZE (buffer) - overhead;
   parse->priv->data_bytecount += data_len;
 
-  if (parse->priv->fps_num) {
-    /* Calculate duration of a frame from frame properties */
-    frame_dur = (GST_SECOND * parse->priv->fps_den) / parse->priv->fps_num;
-    parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
-        (parse->priv->framecount * frame_dur);
-
-  } else if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
+  /* duration should be valid by now,
+   * either set by subclass or maybe based on fps settings */
+  if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
     /* Calculate duration of a frame from buffer properties */
     frame_dur = GST_BUFFER_DURATION (buffer);
     parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
@@ -1048,6 +1149,9 @@ gst_base_parse_update_bitrates (GstBaseParse * parse, GstBuffer * buffer)
   /* override if subclass provided bitrate, e.g. metadata based */
   if (parse->priv->bitrate) {
     parse->priv->avg_bitrate = parse->priv->bitrate;
+    /* spread this (confirmed) info ASAP */
+    if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
+      gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
   }
 
   frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
@@ -1055,27 +1159,30 @@ gst_base_parse_update_bitrates (GstBaseParse * parse, GstBuffer * buffer)
   GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
       parse->priv->avg_bitrate);
 
-  if (frame_bitrate < parse->priv->min_bitrate) {
-    parse->priv->min_bitrate = frame_bitrate;
-    update_min = TRUE;
-  }
-
-  if (frame_bitrate > parse->priv->max_bitrate) {
-    parse->priv->max_bitrate = frame_bitrate;
-    update_max = TRUE;
-  }
+  if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
+    goto exit;
+  } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
+    /* always post all at threshold time */
+    update_min = update_max = update_avg = TRUE;
+  } else {
+    if (frame_bitrate < parse->priv->min_bitrate) {
+      parse->priv->min_bitrate = frame_bitrate;
+      update_min = TRUE;
+    }
 
-  old_avg_bitrate = parse->priv->posted_avg_bitrate;
-  if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold ||
-      (gint) (parse->priv->avg_bitrate - old_avg_bitrate) > update_threshold)
-    update_avg = TRUE;
+    if (frame_bitrate > parse->priv->max_bitrate) {
+      parse->priv->max_bitrate = frame_bitrate;
+      update_max = TRUE;
+    }
 
-  /* always post all at threshold time */
-  if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE)
-    gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
+    old_avg_bitrate = parse->priv->posted_avg_bitrate;
+    if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
+        || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
+        update_threshold)
+      update_avg = TRUE;
+  }
 
-  if (parse->priv->framecount > MIN_FRAMES_TO_POST_BITRATE &&
-      (update_min || update_avg || update_max))
+  if ((update_min || update_avg || update_max))
     gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
 
   /* If average bitrate changes that much and no valid (time) duration provided,
@@ -1085,6 +1192,9 @@ gst_base_parse_update_bitrates (GstBaseParse * parse, GstBuffer * buffer)
           GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
     gst_element_post_message (GST_ELEMENT (parse),
         gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
+
+exit:
+  return;
 }
 
 /**
@@ -1119,6 +1229,8 @@ gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
       goto exit;
     }
 
+    /* FIXME need better helper data structure that handles these issues
+     * related to ongoing collecting of index entries */
     if (parse->priv->index_last_offset >= offset) {
       GST_DEBUG_OBJECT (parse, "already have entries up to offset "
           "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
@@ -1131,6 +1243,21 @@ gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
           GST_TIME_ARGS (parse->priv->index_last_ts));
       goto exit;
     }
+
+    /* if last is not really the last one */
+    if (!parse->priv->index_last_valid) {
+      GstClockTime prev_ts;
+
+      gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
+      if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
+        GST_DEBUG_OBJECT (parse,
+            "entry too close to existing entry %" GST_TIME_FORMAT,
+            GST_TIME_ARGS (prev_ts));
+        parse->priv->index_last_offset = offset;
+        parse->priv->index_last_ts = ts;
+        goto exit;
+      }
+    }
   }
 
   associations[0].format = GST_FORMAT_TIME;
@@ -1145,8 +1272,10 @@ gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
       2, (const GstIndexAssociation *) &associations);
   GST_OBJECT_UNLOCK (parse);
 
-  parse->priv->index_last_offset = offset;
-  parse->priv->index_last_ts = ts;
+  if (key) {
+    parse->priv->index_last_offset = offset;
+    parse->priv->index_last_ts = ts;
+  }
 
   ret = TRUE;
 
@@ -1202,11 +1331,50 @@ done:
   GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
       G_GUINT64_FORMAT ")", seekable, start, stop);
   parse->priv->upstream_seekable = seekable;
+  parse->priv->upstream_size = seekable ? stop : 0;
 
   GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
   parse->priv->idx_interval = idx_interval * GST_MSECOND;
 }
 
+/* some misc checks on upstream */
+static void
+gst_base_parse_check_upstream (GstBaseParse * parse)
+{
+  GstFormat fmt = GST_FORMAT_TIME;
+  gint64 stop;
+
+  if (gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop))
+    if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
+      /* upstream has one, accept it also, and no further updates */
+      gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
+      parse->priv->upstream_has_duration = TRUE;
+    }
+
+  GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
+      parse->priv->upstream_has_duration);
+}
+
+/* checks src caps to determine if dealing with audio or video */
+/* TODO maybe forego automagic stuff and let subclass configure it ? */
+static void
+gst_base_parse_check_media (GstBaseParse * parse)
+{
+  GstCaps *caps;
+  GstStructure *s;
+
+  caps = GST_PAD_CAPS (parse->srcpad);
+  if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
+    parse->priv->is_video =
+        g_str_has_prefix (gst_structure_get_name (s), "video");
+  } else {
+    /* historical default */
+    parse->priv->is_video = FALSE;
+  }
+
+  GST_DEBUG_OBJECT (parse, "media is video == %d", parse->priv->is_video);
+}
+
 /**
  * gst_base_parse_handle_and_push_buffer:
  * @parse: #GstBaseParse.
@@ -1225,6 +1393,7 @@ gst_base_parse_handle_and_push_buffer (GstBaseParse * parse,
     GstBaseParseClass * klass, GstBuffer * buffer)
 {
   GstFlowReturn ret;
+  gint64 offset;
 
   if (parse->priv->discont) {
     GST_DEBUG_OBJECT (parse, "marking DISCONT");
@@ -1232,14 +1401,47 @@ gst_base_parse_handle_and_push_buffer (GstBaseParse * parse,
     parse->priv->discont = FALSE;
   }
 
+  /* some one-time start-up */
+  if (G_UNLIKELY (!parse->priv->framecount)) {
+    gst_base_parse_check_seekability (parse);
+    gst_base_parse_check_upstream (parse);
+  }
+
   GST_LOG_OBJECT (parse,
       "parsing frame at offset %" G_GUINT64_FORMAT
       " (%#" G_GINT64_MODIFIER "x) of size %d",
       GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
       GST_BUFFER_SIZE (buffer));
 
+  /* store offset as it might get overwritten */
+  offset = GST_BUFFER_OFFSET (buffer);
   ret = klass->parse_frame (parse, buffer);
 
+  /* check initial frame to determine if subclass/format can provide ts.
+   * If so, that allows and enables extra seek and duration determining options */
+  if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
+    if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
+      parse->priv->first_frame_offset = offset;
+      parse->priv->first_frame_ts = GST_BUFFER_TIMESTAMP (buffer);
+      GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
+          " for first frame at offset %" G_GINT64_FORMAT,
+          GST_TIME_ARGS (parse->priv->first_frame_ts),
+          parse->priv->first_frame_offset);
+      if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
+        gint64 off;
+        GstClockTime last_ts = G_MAXINT64;
+
+        GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
+        gst_base_parse_locate_time (parse, &last_ts, &off);
+        if (GST_CLOCK_TIME_IS_VALID (last_ts))
+          gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
+      }
+    } else {
+      /* disable further checks */
+      parse->priv->first_frame_offset = 0;
+    }
+  }
+
   /* re-use default handler to add missing metadata as-much-as-possible */
   gst_base_parse_parse_frame (parse, buffer);
   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
@@ -1253,6 +1455,12 @@ gst_base_parse_handle_and_push_buffer (GstBaseParse * parse,
     parse->priv->next_ts = GST_CLOCK_TIME_NONE;
   }
 
+  if (parse->priv->upstream_seekable && parse->priv->exact_position &&
+      GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
+    gst_base_parse_add_index_entry (parse, offset,
+        GST_BUFFER_TIMESTAMP (buffer),
+        !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
+
   /* First buffers are dropped, this means that the subclass needs more
    * frames to decide on the format and queues them internally */
   /* convert internal flow to OK and mark discont for the next buffer. */
@@ -1292,11 +1500,6 @@ gst_base_parse_push_buffer (GstBaseParse * parse, GstBuffer * buffer)
       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
 
-  /* some one-time start-up */
-  if (G_UNLIKELY (!parse->priv->framecount)) {
-    gst_base_parse_check_seekability (parse);
-  }
-
   /* update stats */
   parse->priv->bytecount += GST_BUFFER_SIZE (buffer);
   if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BASE_PARSE_BUFFER_FLAG_NO_FRAME)) {
@@ -1310,8 +1513,6 @@ gst_base_parse_push_buffer (GstBaseParse * parse, GstBuffer * buffer)
       (parse->priv->framecount % parse->priv->update_interval) == 0)
     gst_base_parse_update_duration (parse);
 
-  gst_base_parse_update_bitrates (parse, buffer);
-
   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
     last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
   if (last_start != GST_CLOCK_TIME_NONE
@@ -1324,13 +1525,13 @@ gst_base_parse_push_buffer (GstBaseParse * parse, GstBuffer * buffer)
   gst_buffer_set_caps (buffer, GST_PAD_CAPS (parse->srcpad));
 
   /* segment adjustment magic; only if we are running the whole show */
-  if (!parse->priv->passthrough &&
+  if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
       (parse->priv->pad_mode == GST_ACTIVATE_PULL ||
           parse->priv->upstream_seekable)) {
     /* segment times are typically estimates,
      * actual frame data might lead subclass to different timestamps,
      * so override segment start from what is supplied there */
-    if (G_UNLIKELY (parse->pending_segment &&
+    if (G_UNLIKELY (parse->pending_segment && !parse->priv->exact_position &&
             GST_CLOCK_TIME_IS_VALID (last_start))) {
       gst_event_unref (parse->pending_segment);
       parse->segment.start =
@@ -1393,26 +1594,26 @@ gst_base_parse_push_buffer (GstBaseParse * parse, GstBuffer * buffer)
   }
 
   /* and should then also be linked downstream, so safe to send some events */
-  if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
-    if (G_UNLIKELY (parse->close_segment)) {
-      GST_DEBUG_OBJECT (parse, "loop sending close segment");
-      gst_pad_push_event (parse->srcpad, parse->close_segment);
-      parse->close_segment = NULL;
-    }
+  if (G_UNLIKELY (parse->close_segment)) {
+    /* only set up by loop */
+    GST_DEBUG_OBJECT (parse, "loop sending close segment");
+    gst_pad_push_event (parse->srcpad, parse->close_segment);
+    parse->close_segment = NULL;
+  }
+  if (G_UNLIKELY (parse->pending_segment)) {
+    GST_DEBUG_OBJECT (parse, "%s push pending segment",
+        parse->priv->pad_mode == GST_ACTIVATE_PULL ? "loop" : "chain");
+    gst_pad_push_event (parse->srcpad, parse->pending_segment);
+    parse->pending_segment = NULL;
 
-    if (G_UNLIKELY (parse->pending_segment)) {
-      GST_DEBUG_OBJECT (parse, "loop push pending segment");
-      gst_pad_push_event (parse->srcpad, parse->pending_segment);
-      parse->pending_segment = NULL;
-    }
-  } else {
-    if (G_UNLIKELY (parse->pending_segment)) {
-      GST_DEBUG_OBJECT (parse, "chain pushing a pending segment");
-      gst_pad_push_event (parse->srcpad, parse->pending_segment);
-      parse->pending_segment = NULL;
-    }
+    /* have caps; check identity */
+    gst_base_parse_check_media (parse);
   }
 
+  /* update bitrates and optionally post corresponding tags
+   * (following newsegment) */
+  gst_base_parse_update_bitrates (parse, buffer);
+
   if (G_UNLIKELY (parse->priv->pending_events)) {
     GList *l;
 
@@ -1423,26 +1624,33 @@ gst_base_parse_push_buffer (GstBaseParse * parse, GstBuffer * buffer)
     parse->priv->pending_events = NULL;
   }
 
-  /* TODO: Add to seek table */
-
   if (klass->pre_push_buffer)
     ret = klass->pre_push_buffer (parse, buffer);
   else
     ret = GST_BASE_PARSE_FLOW_CLIP;
 
+  parse->priv->seen_keyframe |= parse->priv->is_video &&
+      !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
+
   if (ret == GST_BASE_PARSE_FLOW_CLIP) {
     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
         GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
-        GST_BUFFER_TIMESTAMP (buffer) > parse->segment.stop) {
+        GST_BUFFER_TIMESTAMP (buffer) >
+        parse->segment.stop + parse->priv->lead_out_ts) {
       GST_LOG_OBJECT (parse, "Dropped frame, after segment");
       ret = GST_FLOW_UNEXPECTED;
     } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
         GST_BUFFER_DURATION_IS_VALID (buffer) &&
         GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
-        GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer)
-        < parse->segment.start) {
-      GST_LOG_OBJECT (parse, "Dropped frame, before segment");
-      ret = GST_BASE_PARSE_FLOW_DROPPED;
+        GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
+        parse->priv->lead_in_ts < parse->segment.start) {
+      if (parse->priv->seen_keyframe) {
+        GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
+        ret = GST_FLOW_OK;
+      } else {
+        GST_LOG_OBJECT (parse, "Dropped frame, before segment");
+        ret = GST_BASE_PARSE_FLOW_DROPPED;
+      }
     } else {
       ret = GST_FLOW_OK;
     }
@@ -1454,9 +1662,17 @@ gst_base_parse_push_buffer (GstBaseParse * parse, GstBuffer * buffer)
     gst_buffer_unref (buffer);
     ret = GST_FLOW_OK;
   } else if (ret == GST_FLOW_OK) {
-    ret = gst_pad_push (parse->srcpad, buffer);
-    GST_LOG_OBJECT (parse, "frame (%d bytes) pushed: %s",
-        GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
+    if (parse->segment.rate > 0.0) {
+      ret = gst_pad_push (parse->srcpad, buffer);
+      GST_LOG_OBJECT (parse, "frame (%d bytes) pushed: %s",
+          GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
+    } else {
+      GST_LOG_OBJECT (parse, "frame (%d bytes) queued for now",
+          GST_BUFFER_SIZE (buffer));
+      parse->priv->buffers_queued =
+          g_slist_prepend (parse->priv->buffers_queued, buffer);
+      ret = GST_FLOW_OK;
+    }
   } else {
     gst_buffer_unref (buffer);
     GST_LOG_OBJECT (parse, "frame (%d bytes) not pushed: %s",
@@ -1513,6 +1729,118 @@ gst_base_parse_drain (GstBaseParse * parse)
   parse->priv->drain = FALSE;
 }
 
+/**
+ * gst_base_parse_process_fragment:
+ * @parse: #GstBaseParse.
+ *
+ * Processes a reverse playback (forward) fragment:
+ * - append head of last fragment that was skipped to current fragment data
+ * - drain the resulting current fragment data (i.e. repeated chain)
+ * - add time/duration (if needed) to frames queued by chain
+ * - push queued data
+ */
+static GstFlowReturn
+gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
+{
+  GstBuffer *buf;
+  GstFlowReturn ret = GST_FLOW_OK;
+  GSList *send = NULL;
+
+  if (push_only)
+    goto push;
+
+  /* restore order */
+  parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
+  while (parse->priv->buffers_pending) {
+    buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
+    GST_LOG_OBJECT (parse, "adding pending buffer (size %d)",
+        GST_BUFFER_SIZE (buf));
+    gst_adapter_push (parse->adapter, buf);
+    parse->priv->buffers_pending =
+        g_slist_delete_link (parse->priv->buffers_pending,
+        parse->priv->buffers_pending);
+  }
+
+  /* invalidate so no fall-back timestamping is performed;
+   * ok if taken from subclass or upstream */
+  parse->priv->next_ts = GST_CLOCK_TIME_NONE;
+  /* prevent it hanging around stop all the time */
+  parse->segment.last_stop = GST_CLOCK_TIME_NONE;
+  /* mark next run */
+  parse->priv->discont = TRUE;
+
+  /* chain looks for frames and queues resulting ones (in stead of pushing) */
+  /* initial skipped data is added to buffers_pending */
+  gst_base_parse_drain (parse);
+
+push:
+  /* add metadata (if needed to queued buffers */
+  GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (parse->priv->last_ts));
+  while (parse->priv->buffers_queued) {
+    buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
+
+    /* no touching if upstream or parsing provided time */
+    if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
+      GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
+          GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
+    } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
+        GST_BUFFER_DURATION_IS_VALID (buf)) {
+      if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
+        parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
+      else
+        parse->priv->last_ts = 0;
+      GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
+      GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
+          GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
+    } else {
+      /* no idea, very bad */
+      GST_WARNING_OBJECT (parse, "could not determine time for buffer");
+    }
+
+    /* reverse order for ascending sending */
+    send = g_slist_prepend (send, buf);
+    parse->priv->buffers_queued =
+        g_slist_delete_link (parse->priv->buffers_queued,
+        parse->priv->buffers_queued);
+  }
+
+  /* send buffers */
+  while (send) {
+    buf = GST_BUFFER_CAST (send->data);
+    GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
+        GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
+        ", offset %" G_GINT64_FORMAT, buf,
+        GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
+        GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
+
+    if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts)))
+      parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
+
+    /* iterate output queue an push downstream */
+    ret = gst_pad_push (parse->srcpad, buf);
+    send = g_slist_delete_link (send, send);
+
+    /* clear any leftover if error */
+    if (G_UNLIKELY (ret != GST_FLOW_OK)) {
+      while (send) {
+        buf = GST_BUFFER_CAST (send->data);
+        gst_buffer_unref (buf);
+        send = g_slist_delete_link (send, send);
+      }
+    }
+  }
+
+  /* any trailing unused no longer usable (ideally none) */
+  if (G_UNLIKELY (gst_adapter_available (parse->adapter))) {
+    GST_DEBUG_OBJECT (parse, "discarding %d trailing bytes",
+        gst_adapter_available (parse->adapter));
+    gst_adapter_clear (parse->adapter);
+  }
+
+  return ret;
+}
+
 /* small helper that checks whether we have been trying to resync too long */
 static inline GstFlowReturn
 gst_base_parse_check_sync (GstBaseParse * parse)
@@ -1546,7 +1874,7 @@ gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
   guint fsize = 0;
   gint skip = -1;
   const guint8 *data;
-  guint min_size;
+  guint min_size, av;
   GstClockTime timestamp;
 
   parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
@@ -1558,8 +1886,18 @@ gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
     if (G_UNLIKELY (parse->priv->passthrough)) {
       buffer = gst_buffer_make_metadata_writable (buffer);
       return gst_base_parse_push_buffer (parse, buffer);
-    } else
+    }
+    /* upstream feeding us in reverse playback;
+     * gather each fragment, then process it in single run */
+    if (parse->segment.rate < 0.0) {
+      if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
+        GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
+        ret = gst_base_parse_process_fragment (parse, FALSE);
+      }
       gst_adapter_push (parse->adapter, buffer);
+      return ret;
+    }
+    gst_adapter_push (parse->adapter, buffer);
   }
 
   /* Parse and push as many frames as possible */
@@ -1569,12 +1907,11 @@ gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
 
     /* Synchronization loop */
     for (;;) {
-      GST_BASE_PARSE_LOCK (parse);
       min_size = parse->priv->min_frame_size;
-      GST_BASE_PARSE_UNLOCK (parse);
+      av = gst_adapter_available (parse->adapter);
 
       if (G_UNLIKELY (parse->priv->drain)) {
-        min_size = gst_adapter_available (parse->adapter);
+        min_size = av;
         GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
         if (G_UNLIKELY (!min_size)) {
           gst_buffer_unref (tmpbuf);
@@ -1583,14 +1920,15 @@ gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
       }
 
       /* Collect at least min_frame_size bytes */
-      if (gst_adapter_available (parse->adapter) < min_size) {
+      if (av < min_size) {
         GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
-            gst_adapter_available (parse->adapter));
+            av);
         gst_buffer_unref (tmpbuf);
         goto done;
       }
 
-      data = gst_adapter_peek (parse->adapter, min_size);
+      /* always pass all available data */
+      data = gst_adapter_peek (parse->adapter, av);
       GST_BUFFER_DATA (tmpbuf) = (guint8 *) data;
       GST_BUFFER_SIZE (tmpbuf) = min_size;
       GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
@@ -1610,23 +1948,33 @@ gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
           gst_buffer_unref (tmpbuf);
           goto done;
         }
+        GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
         break;
       }
+      if (skip == -1) {
+        /* subclass didn't touch this value. By default we skip 1 byte */
+        skip = 1;
+      }
       if (skip > 0) {
         GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
-        gst_adapter_flush (parse->adapter, skip);
+        if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
+          /* reverse playback, and no frames found yet, so we are skipping
+           * the leading part of a fragment, which may form the tail of
+           * fragment coming later, hopefully subclass skips efficiently ... */
+          timestamp = gst_adapter_prev_timestamp (parse->adapter, NULL);
+          outbuf = gst_adapter_take_buffer (parse->adapter, skip);
+          outbuf = gst_buffer_make_metadata_writable (outbuf);
+          GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
+          parse->priv->buffers_pending =
+              g_slist_prepend (parse->priv->buffers_pending, outbuf);
+          outbuf = NULL;
+        } else {
+          gst_adapter_flush (parse->adapter, skip);
+        }
         parse->priv->offset += skip;
         if (!parse->priv->discont)
           parse->priv->sync_offset = parse->priv->offset;
         parse->priv->discont = TRUE;
-      } else if (skip == -1) {
-        /* subclass didn't touch this value. By default we skip 1 byte */
-        GST_LOG_OBJECT (parse, "finding sync, skipping 1 byte");
-        gst_adapter_flush (parse->adapter, 1);
-        parse->priv->offset++;
-        if (!parse->priv->discont)
-          parse->priv->sync_offset = parse->priv->offset;
-        parse->priv->discont = TRUE;
       }
       /* There is a possibility that subclass set the skip value to zero.
          This means that it has probably found a frame but wants to ask
@@ -1663,6 +2011,7 @@ gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
     /* Subclass may want to know the data offset */
     GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
     parse->priv->offset += fsize;
+    GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
 
     /* move along with upstream timestamp (if any),
      * but interpolate in between */
@@ -1760,39 +2109,89 @@ gst_base_parse_pull_range (GstBaseParse * parse, guint size,
   return GST_FLOW_OK;
 }
 
-/**
- * gst_base_parse_loop:
- * @pad: GstPad
- *
- * Loop that is used in pull mode to retrieve data from upstream.
- */
-static void
-gst_base_parse_loop (GstPad * pad)
+static GstFlowReturn
+gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
+{
+  gint64 offset = 0;
+  GstClockTime ts = 0;
+  GstBuffer *buffer;
+  GstFlowReturn ret;
+
+  GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
+      ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
+      parse->priv->last_offset);
+
+  if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
+    GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
+        GST_TIME_ARGS (parse->segment.start));
+    ret = GST_FLOW_UNEXPECTED;
+    goto exit;
+  }
+
+  /* last fragment started at last_offset / last_ts;
+   * seek back 10s capped at 1MB */
+  if (parse->priv->last_ts >= 10 * GST_SECOND)
+    ts = parse->priv->last_ts - 10 * GST_SECOND;
+  /* if we are exact now, we will be more so going backwards */
+  if (parse->priv->exact_position) {
+    offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
+  } else {
+    GstFormat dstformat = GST_FORMAT_BYTES;
+
+    if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
+            &dstformat, &offset)) {
+      GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
+    }
+  }
+  offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
+      parse->priv->last_offset - 1024);
+  offset = MAX (0, offset);
+
+  GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
+      offset);
+  parse->priv->offset = offset;
+
+  ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
+      &buffer);
+  if (ret != GST_FLOW_OK)
+    goto exit;
+
+  /* offset will increase again as fragment is processed/parsed */
+  parse->priv->last_offset = offset;
+
+  gst_adapter_push (parse->adapter, buffer);
+  ret = gst_base_parse_process_fragment (parse, FALSE);
+  if (ret != GST_FLOW_OK)
+    goto exit;
+
+  /* force previous fragment */
+  parse->priv->offset = -1;
+
+exit:
+  return ret;
+}
+
+/* PULL mode:
+ * pull and scan for next frame starting from current offset
+ * ajusts sync, drain and offset going along */
+static GstFlowReturn
+gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass,
+    GstBuffer ** buf, gboolean full)
 {
-  GstBaseParse *parse;
-  GstBaseParseClass *klass;
   GstBuffer *buffer, *outbuf;
-  gboolean ret = FALSE;
+  GstFlowReturn ret = GST_FLOW_OK;
   guint fsize = 0, min_size;
   gint skip = 0;
 
-  parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
-  klass = GST_BASE_PARSE_GET_CLASS (parse);
-
-  /* TODO: Check if we reach segment stop limit */
+  g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
 
   while (TRUE) {
 
-    GST_BASE_PARSE_LOCK (parse);
     min_size = parse->priv->min_frame_size;
-    GST_BASE_PARSE_UNLOCK (parse);
 
     ret = gst_base_parse_pull_range (parse, min_size, &buffer);
-
-    if (ret == GST_FLOW_UNEXPECTED)
-      goto eos;
-    else if (ret != GST_FLOW_OK)
-      goto pause;
+    if (ret != GST_FLOW_OK)
+      goto done;
 
     if (parse->priv->discont) {
       GST_DEBUG_OBJECT (parse, "marking DISCONT");
@@ -1807,21 +2206,27 @@ gst_base_parse_loop (GstPad * pad)
     skip = -1;
     if (klass->check_valid_frame (parse, buffer, &fsize, &skip)) {
       parse->priv->drain = FALSE;
+      GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
       break;
     }
     parse->priv->drain = FALSE;
+    if (skip == -1)
+      skip = 1;
     if (skip > 0) {
       GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
+      if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
+        /* reverse playback, and no frames found yet, so we are skipping
+         * the leading part of a fragment, which may form the tail of
+         * fragment coming later, hopefully subclass skips efficiently ... */
+        outbuf = gst_buffer_create_sub (buffer, 0, skip);
+        parse->priv->buffers_pending =
+            g_slist_prepend (parse->priv->buffers_pending, outbuf);
+        outbuf = NULL;
+      }
       parse->priv->offset += skip;
       if (!parse->priv->discont)
         parse->priv->sync_offset = parse->priv->offset;
       parse->priv->discont = TRUE;
-    } else if (skip == -1) {
-      GST_LOG_OBJECT (parse, "finding sync, skipping 1 byte");
-      parse->priv->offset++;
-      if (!parse->priv->discont)
-        parse->priv->sync_offset = parse->priv->offset;
-      parse->priv->discont = TRUE;
     }
     /* skip == 0 should imply subclass set min_size to need more data ... */
     GST_DEBUG_OBJECT (parse, "finding sync...");
@@ -1831,35 +2236,89 @@ gst_base_parse_loop (GstPad * pad)
     }
   }
 
-  if (fsize <= GST_BUFFER_SIZE (buffer)) {
-    outbuf = gst_buffer_create_sub (buffer, 0, fsize);
-    GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer);
+  /* Does the subclass want to skip too? */
+  if (skip > 0)
+    parse->priv->offset += skip;
+  else if (skip < 0)
+    skip = 0;
+
+  if (fsize + skip <= GST_BUFFER_SIZE (buffer)) {
+    outbuf = gst_buffer_create_sub (buffer, skip, fsize);
+    GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
+    GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
     gst_buffer_unref (buffer);
   } else {
     gst_buffer_unref (buffer);
     ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
-
-    if (ret == GST_FLOW_UNEXPECTED)
-      goto eos;
-    else if (ret != GST_FLOW_OK)
-      goto pause;
-    if (GST_BUFFER_SIZE (outbuf) < fsize)
-      goto eos;
+    if (ret != GST_FLOW_OK)
+      goto done;
+    if (GST_BUFFER_SIZE (outbuf) < fsize) {
+      gst_buffer_unref (outbuf);
+      ret = GST_FLOW_UNEXPECTED;
+    }
   }
 
   parse->priv->offset += fsize;
 
-  /* Does the subclass want to skip too? */
-  if (skip > 0)
-    parse->priv->offset += skip;
+  *buf = outbuf;
+
+done:
+  return ret;
+}
+
+/**
+ * gst_base_parse_loop:
+ * @pad: GstPad
+ *
+ * Loop that is used in pull mode to retrieve data from upstream.
+ */
+static void
+gst_base_parse_loop (GstPad * pad)
+{
+  GstBaseParse *parse;
+  GstBaseParseClass *klass;
+  GstBuffer *outbuf;
+  GstFlowReturn ret = GST_FLOW_OK;
+
+  parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
+  klass = GST_BASE_PARSE_GET_CLASS (parse);
+
+  /* reverse playback:
+   * first fragment (closest to stop time) is handled normally below,
+   * then we pull in fragments going backwards */
+  if (parse->segment.rate < 0.0) {
+    /* check if we jumped back to a previous fragment,
+     * which is a post-first fragment */
+    if (parse->priv->offset < 0) {
+      ret = gst_base_parse_handle_previous_fragment (parse);
+      goto done;
+    }
+  }
+
+  ret = gst_base_parse_scan_frame (parse, klass, &outbuf, TRUE);
+  if (ret != GST_FLOW_OK)
+    goto done;
 
   /* This always unrefs the outbuf, even if error occurs */
   ret = gst_base_parse_handle_and_push_buffer (parse, klass, outbuf);
 
-  if (ret != GST_FLOW_OK)
-    goto pause;
+  /* eat expected eos signalling past segment in reverse playback */
+  if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
+      parse->segment.last_stop >= parse->segment.stop) {
+    GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
+    /* push what was accumulated during loop run */
+    gst_base_parse_process_fragment (parse, TRUE);
+    /* force previous fragment */
+    parse->priv->offset = -1;
+    ret = GST_FLOW_OK;
+  }
 
 done:
+  if (ret == GST_FLOW_UNEXPECTED)
+    goto eos;
+  else if (ret != GST_FLOW_OK)
+    goto pause;
+
   gst_object_unref (parse);
   return;
 
@@ -1954,7 +2413,7 @@ gst_base_parse_sink_activate (GstPad * sinkpad)
 /**
  * gst_base_parse_activate:
  * @parse: #GstBaseParse.
- * @active: TRUE if element will be activated, FALSE if disactivated.
+ * @active: TRUE if element will be activated, FALSE if deactivated.
  *
  * Returns: TRUE if the operation succeeded.
  */
@@ -2064,15 +2523,21 @@ gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
  * @duration: duration value.
  *
  * Sets the duration of the currently playing media. Subclass can use this
- * when it notices a change in the media duration.
- */
+ * when it is able to determine duration and/or notices a change in the media
+ * duration.  Alternatively, if @interval is non-zero (default), then stream
+ * duration is determined based on estimated bitrate, and updated every @interval
+ * frames. */
 void
 gst_base_parse_set_duration (GstBaseParse * parse,
-    GstFormat fmt, gint64 duration)
+    GstFormat fmt, gint64 duration, gint interval)
 {
   g_return_if_fail (parse != NULL);
 
-  GST_BASE_PARSE_LOCK (parse);
+  if (parse->priv->upstream_has_duration) {
+    GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
+    goto exit;
+  }
+
   if (duration != parse->priv->duration) {
     GstMessage *m;
 
@@ -2084,7 +2549,16 @@ gst_base_parse_set_duration (GstBaseParse * parse,
   parse->priv->duration = duration;
   parse->priv->duration_fmt = fmt;
   GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
-  GST_BASE_PARSE_UNLOCK (parse);
+  if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
+    if (interval != 0) {
+      GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
+      interval = 0;
+    }
+  }
+  GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
+  parse->priv->update_interval = interval;
+exit:
+  return;
 }
 
 /**
@@ -2106,6 +2580,7 @@ gst_base_parse_set_seek (GstBaseParse * parse,
 {
   parse->priv->seekable = seek;
   parse->priv->bitrate = bitrate;
+  GST_DEBUG_OBJECT (parse, "seek %d, bitrate %d", seek, bitrate);
 }
 
 
@@ -2123,15 +2598,13 @@ gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
 {
   g_return_if_fail (parse != NULL);
 
-  GST_BASE_PARSE_LOCK (parse);
   parse->priv->min_frame_size = min_size;
   GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
-  GST_BASE_PARSE_UNLOCK (parse);
 }
 
 /**
- * gst_base_transform_set_passthrough:
- * @trans: the #GstBaseParse to set
+ * gst_base_parse_set_passthrough:
+ * @parse: the #GstBaseParse to set
  * @passthrough: boolean indicating passthrough mode.
  *
  * Set passthrough mode for this parser.  If operating in passthrough,
@@ -2142,53 +2615,59 @@ gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
 {
   g_return_if_fail (parse != NULL);
 
-  GST_BASE_PARSE_LOCK (parse);
   parse->priv->passthrough = passthrough;
   GST_LOG_OBJECT (parse, "set passthrough: %d", passthrough);
-  GST_BASE_PARSE_UNLOCK (parse);
 }
 
 /**
- * gst_base_transform_set_frame_props:
+ * gst_base_parse_set_frame_props:
  * @parse: the #GstBaseParse to set
  * @fps_num: frames per second (numerator).
  * @fps_den: frames per second (denominator).
- * @interval: duration update interval in frames.
+ * @lead_in: frames needed before a segment for subsequent decode
+ * @lead_out: frames needed after a segment
  *
  * If frames per second is configured, parser can take care of buffer duration
- * and timestamping. If #interval is non-zero (default), then stream duration
- * is determined based on frame and byte counts, and updated every #interval
- * frames.
+ * and timestamping.  When performing segment clipping, or seeking to a specific
+ * location, a corresponding decoder might need an initial @lead_in and a
+ * following @lead_out number of frames to ensure the desired segment is
+ * entirely filled upon decoding.
  */
 void
 gst_base_parse_set_frame_props (GstBaseParse * parse, guint fps_num,
-    guint fps_den, gint interval)
+    guint fps_den, guint lead_in, guint lead_out)
 {
   g_return_if_fail (parse != NULL);
 
-  GST_BASE_PARSE_LOCK (parse);
   parse->priv->fps_num = fps_num;
   parse->priv->fps_den = fps_den;
-  parse->priv->update_interval = interval;
   if (!fps_num || !fps_den) {
     GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
         fps_num, fps_den);
     fps_num = fps_den = 0;
-    interval = 0;
     parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
+    parse->priv->lead_in = parse->priv->lead_out = 0;
+    parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
   } else {
     parse->priv->frame_duration =
-        gst_util_uint64_scale (GST_SECOND, parse->priv->fps_den,
-        parse->priv->fps_num);
+        gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
+    parse->priv->lead_in = lead_in;
+    parse->priv->lead_out = lead_out;
+    parse->priv->lead_in_ts =
+        gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
+    parse->priv->lead_out_ts =
+        gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
   }
   GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
       fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
-  GST_LOG_OBJECT (parse, "set update interval: %d", interval);
-  GST_BASE_PARSE_UNLOCK (parse);
+  GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
+      "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
+      lead_in, parse->priv->lead_in_ts / GST_MSECOND,
+      lead_out, parse->priv->lead_out_ts / GST_MSECOND);
 }
 
 /**
- * gst_base_transform_get_sync:
+ * gst_base_parse_get_sync:
  * @parse: the #GstBaseParse to query
  *
  * Returns: TRUE if parser is considered 'in sync'.  That is, frames have been
@@ -2201,17 +2680,15 @@ gst_base_parse_get_sync (GstBaseParse * parse)
 
   g_return_val_if_fail (parse != NULL, FALSE);
 
-  GST_BASE_PARSE_LOCK (parse);
   /* losing sync is pretty much a discont (and vice versa), no ? */
   ret = !parse->priv->discont;
-  GST_BASE_PARSE_UNLOCK (parse);
 
   GST_DEBUG_OBJECT (parse, "sync: %d", ret);
   return ret;
 }
 
 /**
- * gst_base_transform_get_drain:
+ * gst_base_parse_get_drain:
  * @parse: the #GstBaseParse to query
  *
  * Returns: TRUE if parser is currently 'draining'.  That is, leftover data
@@ -2224,10 +2701,8 @@ gst_base_parse_get_drain (GstBaseParse * parse)
 
   g_return_val_if_fail (parse != NULL, FALSE);
 
-  GST_BASE_PARSE_LOCK (parse);
   /* losing sync is pretty much a discont (and vice versa), no ? */
   ret = parse->priv->drain;
-  GST_BASE_PARSE_UNLOCK (parse);
 
   GST_DEBUG_OBJECT (parse, "drain: %d", ret);
   return ret;
@@ -2294,11 +2769,9 @@ static gboolean
 gst_base_parse_query (GstPad * pad, GstQuery * query)
 {
   GstBaseParse *parse;
-  GstBaseParseClass *klass;
   gboolean res = FALSE;
 
   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
-  klass = GST_BASE_PARSE_GET_CLASS (parse);
 
   GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
 
@@ -2311,7 +2784,7 @@ gst_base_parse_query (GstPad * pad, GstQuery * query)
       GST_DEBUG_OBJECT (parse, "position query");
       gst_query_parse_position (query, &format, NULL);
 
-      g_mutex_lock (parse->parse_lock);
+      GST_OBJECT_LOCK (parse);
       if (format == GST_FORMAT_BYTES) {
         dest_value = parse->priv->offset;
         res = TRUE;
@@ -2320,7 +2793,7 @@ gst_base_parse_query (GstPad * pad, GstQuery * query)
         dest_value = parse->segment.last_stop;
         res = TRUE;
       }
-      g_mutex_unlock (parse->parse_lock);
+      GST_OBJECT_UNLOCK (parse);
 
       if (res)
         gst_query_set_position (query, format, dest_value);
@@ -2329,10 +2802,8 @@ gst_base_parse_query (GstPad * pad, GstQuery * query)
         if (!res) {
           /* no precise result, upstream no idea either, then best estimate */
           /* priv->offset is updated in both PUSH/PULL modes */
-          g_mutex_lock (parse->parse_lock);
           res = gst_base_parse_convert (parse,
               GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
-          g_mutex_unlock (parse->parse_lock);
         }
       }
       break;
@@ -2350,9 +2821,7 @@ gst_base_parse_query (GstPad * pad, GstQuery * query)
 
       /* otherwise best estimate from us */
       if (!res) {
-        g_mutex_lock (parse->parse_lock);
         res = gst_base_parse_get_duration (parse, format, &duration);
-        g_mutex_unlock (parse->parse_lock);
         if (res)
           gst_query_set_duration (query, format, duration);
       }
@@ -2378,23 +2847,13 @@ gst_base_parse_query (GstPad * pad, GstQuery * query)
         GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
             res, seekable);
         if (!(res && seekable)) {
-          /* TODO maybe also check upstream provides proper duration ? */
-          seekable = TRUE;
           if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
               || duration == -1) {
             seekable = FALSE;
           } else {
-            GstQuery *q;
-
-            q = gst_query_new_seeking (GST_FORMAT_BYTES);
-            if (!gst_pad_peer_query (parse->sinkpad, q)) {
-              seekable = FALSE;
-            } else {
-              gst_query_parse_seeking (q, &fmt, &seekable, NULL, NULL);
-            }
-            GST_LOG_OBJECT (parse, "upstream BYTE handled %d, seekable %d",
-                res, seekable);
-            gst_query_unref (q);
+            seekable = parse->priv->upstream_seekable;
+            GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
+                seekable);
           }
           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
           res = TRUE;
@@ -2429,6 +2888,251 @@ gst_base_parse_query (GstPad * pad, GstQuery * query)
   return res;
 }
 
+/* scans for a cluster start from @pos,
+ * return GST_FLOW_OK and frame position/time in @pos/@time if found */
+static GstFlowReturn
+gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
+    GstClockTime * time, GstClockTime * duration)
+{
+  GstBaseParseClass *klass;
+  gint64 orig_offset;
+  gboolean orig_drain, orig_discont;
+  GstFlowReturn ret = GST_FLOW_OK;
+  GstBuffer *buf = NULL;
+
+  g_return_val_if_fail (GST_FLOW_ERROR, pos != NULL);
+  g_return_val_if_fail (GST_FLOW_ERROR, time != NULL);
+  g_return_val_if_fail (GST_FLOW_ERROR, duration != NULL);
+
+  klass = GST_BASE_PARSE_GET_CLASS (parse);
+
+  *time = GST_CLOCK_TIME_NONE;
+  *duration = GST_CLOCK_TIME_NONE;
+
+  /* save state */
+  orig_offset = parse->priv->offset;
+  orig_discont = parse->priv->discont;
+  orig_drain = parse->priv->drain;
+
+  GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
+      " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
+
+  /* jump elsewhere and locate next frame */
+  parse->priv->offset = *pos;
+  ret = gst_base_parse_scan_frame (parse, klass, &buf, FALSE);
+  if (ret != GST_FLOW_OK)
+    goto done;
+
+  GST_LOG_OBJECT (parse,
+      "peek parsing frame at offset %" G_GUINT64_FORMAT
+      " (%#" G_GINT64_MODIFIER "x) of size %d",
+      GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf), GST_BUFFER_SIZE (buf));
+
+  /* get offset first, subclass parsing might dump other stuff in there */
+  *pos = GST_BUFFER_OFFSET (buf);
+  ret = klass->parse_frame (parse, buf);
+
+  /* but it should provide proper time */
+  *time = GST_BUFFER_TIMESTAMP (buf);
+  *duration = GST_BUFFER_DURATION (buf);
+  gst_buffer_unref (buf);
+
+  GST_LOG_OBJECT (parse,
+      "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
+      GST_TIME_ARGS (*time), *pos);
+
+done:
+  /* restore state */
+  parse->priv->offset = orig_offset;
+  parse->priv->discont = orig_discont;
+  parse->priv->drain = orig_drain;
+
+  return ret;
+}
+
+/* bisect and scan through file for frame starting before @time,
+ * returns OK and @time/@offset if found, NONE and/or error otherwise
+ * If @time == G_MAXINT64, scan for duration ( == last frame) */
+static GstFlowReturn
+gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
+    gint64 * _offset)
+{
+  GstFlowReturn ret = GST_FLOW_OK;
+  gint64 lpos, hpos, newpos;
+  GstClockTime time, ltime, htime, newtime, dur;
+  gboolean cont = TRUE;
+  const GstClockTime tolerance = TARGET_DIFFERENCE;
+  const guint chunk = 4 * 1024;
+
+  g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
+  g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
+
+  /* TODO also make keyframe aware if useful some day */
+
+  time = *_time;
+
+  /* basic cases */
+  if (time == 0) {
+    *_offset = 0;
+    return GST_FLOW_OK;
+  }
+
+  if (time == -1) {
+    *_offset = -1;
+    return GST_FLOW_OK;
+  }
+
+  /* do not know at first */
+  *_offset = -1;
+  *_time = GST_CLOCK_TIME_NONE;
+
+  /* need initial positions; start and end */
+  lpos = parse->priv->first_frame_offset;
+  ltime = parse->priv->first_frame_ts;
+  htime = parse->priv->duration;
+  hpos = parse->priv->upstream_size;
+
+  /* check preconditions are satisfied;
+   * start and end are needed, except for special case where we scan for
+   * last frame to determine duration */
+  if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
+      !GST_CLOCK_TIME_IS_VALID (ltime) ||
+      (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
+    return GST_FLOW_OK;
+  }
+
+  /* shortcut cases */
+  if (time < ltime) {
+    goto exit;
+  } else if (time < ltime + tolerance) {
+    *_offset = lpos;
+    *_time = ltime;
+    goto exit;
+  } else if (time >= htime) {
+    *_offset = hpos;
+    *_time = htime;
+    goto exit;
+  }
+
+  while (htime > ltime && cont) {
+    GST_LOG_OBJECT (parse,
+        "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
+        GST_TIME_ARGS (ltime));
+    GST_LOG_OBJECT (parse,
+        "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
+        GST_TIME_ARGS (htime));
+    if (G_UNLIKELY (time == G_MAXINT64)) {
+      newpos = hpos;
+    } else if (G_LIKELY (hpos > lpos)) {
+      newpos =
+          gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
+          lpos - chunk;
+    } else {
+      /* should mean lpos == hpos, since lpos <= hpos is invariant */
+      newpos = lpos;
+      /* we check this case once, but not forever, so break loop */
+      cont = FALSE;
+    }
+
+    /* ensure */
+    newpos = CLAMP (newpos, lpos, hpos);
+    GST_LOG_OBJECT (parse,
+        "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
+        GST_TIME_ARGS (time), newpos);
+
+    ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
+    if (ret == GST_FLOW_UNEXPECTED) {
+      /* heuristic HACK */
+      hpos = MAX (lpos, hpos - chunk);
+      continue;
+    } else if (ret != GST_FLOW_OK) {
+      goto exit;
+    }
+
+    if (newtime == -1 || newpos == -1) {
+      GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
+      break;
+    }
+
+    if (G_UNLIKELY (time == G_MAXINT64)) {
+      *_offset = newpos;
+      *_time = newtime;
+      if (GST_CLOCK_TIME_IS_VALID (dur))
+        *_time += dur;
+      break;
+    } else if (newtime > time) {
+      /* overshoot */
+      hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
+      htime = newtime;
+    } else if (newtime + tolerance > time) {
+      /* close enough undershoot */
+      *_offset = newpos;
+      *_time = newtime;
+      break;
+    } else if (newtime < ltime) {
+      /* so a position beyond lpos resulted in earlier time than ltime ... */
+      GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
+      break;
+    } else {
+      /* undershoot too far */
+      newpos += newpos == lpos ? chunk : 0;
+      lpos = CLAMP (newpos, lpos, hpos);
+      ltime = newtime;
+    }
+  }
+
+exit:
+  GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
+      GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
+  return ret;
+}
+
+static gint64
+gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
+    gboolean before, GstClockTime * _ts)
+{
+  gint64 bytes = 0, ts = 0;
+  GstIndexEntry *entry = NULL;
+
+  if (time == GST_CLOCK_TIME_NONE) {
+    ts = time;
+    bytes = -1;
+    goto exit;
+  }
+
+  GST_OBJECT_LOCK (parse);
+  if (parse->priv->index) {
+    /* Let's check if we have an index entry for that time */
+    entry = gst_index_get_assoc_entry (parse->priv->index,
+        parse->priv->index_id,
+        before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
+        GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
+  }
+
+  if (entry) {
+    gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
+    gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
+
+    GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
+        " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
+        GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
+  } else {
+    GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
+        GST_TIME_ARGS (time));
+    if (!before) {
+      bytes = -1;
+      ts = GST_CLOCK_TIME_NONE;
+    }
+  }
+  GST_OBJECT_UNLOCK (parse);
+
+exit:
+  if (_ts)
+    *_ts = ts;
+
+  return bytes;
+}
+
 
 /**
  * gst_base_parse_handle_seek:
@@ -2440,28 +3144,26 @@ gst_base_parse_query (GstPad * pad, GstQuery * query)
 static gboolean
 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
 {
-  GstBaseParseClass *klass;
   gdouble rate;
   GstFormat format;
   GstSeekFlags flags;
   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
-  gboolean flush, update, res = TRUE;
-  gint64 cur, stop, seekpos;
+  gboolean flush, update, res = TRUE, accurate;
+  gint64 cur, stop, seekpos, seekstop;
   GstSegment seeksegment = { 0, };
   GstFormat dstformat;
-
-  klass = GST_BASE_PARSE_GET_CLASS (parse);
+  GstClockTime start_ts;
 
   gst_event_parse_seek (event, &rate, &format, &flags,
       &cur_type, &cur, &stop_type, &stop);
 
-  GST_DEBUG_OBJECT (parse, "seek to format %s, "
+  GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
       "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
-      GST_TIME_FORMAT, gst_format_get_name (format),
+      GST_TIME_FORMAT, gst_format_get_name (format), rate,
       cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
 
-  /* no negative rates yet */
-  if (rate < 0.0)
+  /* no negative rates in push mode */
+  if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
     goto negative_rate;
 
   if (cur_type != GST_SEEK_TYPE_SET ||
@@ -2492,14 +3194,44 @@ gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
   gst_segment_set_seek (&seeksegment, rate, format, flags,
       cur_type, cur, stop_type, stop, &update);
 
-  dstformat = GST_FORMAT_BYTES;
-  if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.last_stop,
-          &dstformat, &seekpos))
-    goto convert_failed;
+  /* accurate seeking implies seek tables are used to obtain position,
+   * and the requested segment is maintained exactly, not adjusted any way */
+  accurate = flags & GST_SEEK_FLAG_ACCURATE;
+
+  /* maybe we can be accurate for (almost) free */
+  gst_base_parse_find_offset (parse, seeksegment.last_stop, TRUE, &start_ts);
+  if (seeksegment.last_stop <= start_ts + TARGET_DIFFERENCE) {
+    GST_DEBUG_OBJECT (parse, "accurate seek possible");
+    accurate = TRUE;
+  }
+  if (accurate) {
+    GstClockTime startpos = seeksegment.last_stop;
+
+    /* accurate requested, so ... seek a bit before target */
+    if (startpos < parse->priv->lead_in_ts)
+      startpos = 0;
+    else
+      startpos -= parse->priv->lead_in_ts;
+    seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
+    seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
+        NULL);
+  } else {
+    start_ts = seeksegment.last_stop;
+    dstformat = GST_FORMAT_BYTES;
+    if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.last_stop,
+            &dstformat, &seekpos))
+      goto convert_failed;
+    if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
+            &dstformat, &seekstop))
+      goto convert_failed;
+  }
 
   GST_DEBUG_OBJECT (parse,
-      "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT, cur,
-      seekpos);
+      "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
+      start_ts, seekpos);
+  GST_DEBUG_OBJECT (parse,
+      "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
+      seeksegment.stop, seekstop);
 
   if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
     gint64 last_stop;
@@ -2510,6 +3242,8 @@ gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
       if (parse->srcpad) {
         GST_DEBUG_OBJECT (parse, "sending flush start");
         gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
+        /* unlock upstream pull_range */
+        gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
       }
     } else {
       gst_pad_pause_task (parse->sinkpad);
@@ -2530,6 +3264,8 @@ gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
     if (flush) {
       GST_DEBUG_OBJECT (parse, "sending flush stop");
       gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
+      gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop ());
+      gst_base_parse_clear_queues (parse);
     } else {
       if (parse->close_segment)
         gst_event_unref (parse->close_segment);
@@ -2558,23 +3294,46 @@ gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
     /* This will be sent later in _loop() */
     parse->pending_segment =
         gst_event_new_new_segment (FALSE, parse->segment.rate,
-        parse->segment.format, parse->segment.last_stop, parse->segment.stop,
-        parse->segment.last_stop);
+        parse->segment.format, parse->segment.start, parse->segment.stop,
+        parse->segment.start);
 
     GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
         "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
         ", pos = %" GST_TIME_FORMAT, format,
-        GST_TIME_ARGS (parse->segment.last_stop),
-        GST_TIME_ARGS (stop), GST_TIME_ARGS (parse->segment.last_stop));
+        GST_TIME_ARGS (parse->segment.start),
+        GST_TIME_ARGS (parse->segment.stop),
+        GST_TIME_ARGS (parse->segment.start));
+
+    /* one last chance in pull mode to stay accurate;
+     * maybe scan and subclass can find where to go */
+    if (!accurate) {
+      gint64 scanpos;
+      GstClockTime ts = seeksegment.last_stop;
+
+      gst_base_parse_locate_time (parse, &ts, &scanpos);
+      if (scanpos >= 0) {
+        accurate = TRUE;
+        seekpos = scanpos;
+        /* running collected index now consists of several intervals,
+         * so optimized check no longer possible */
+        parse->priv->index_last_valid = FALSE;
+        parse->priv->index_last_offset = 0;
+        parse->priv->index_last_ts = 0;
+      }
+    }
 
     /* mark discont if we are going to stream from another position. */
     if (seekpos != parse->priv->offset) {
       GST_DEBUG_OBJECT (parse,
           "mark DISCONT, we did a seek to another position");
       parse->priv->offset = seekpos;
+      parse->priv->last_offset = seekpos;
+      parse->priv->seen_keyframe = FALSE;
       parse->priv->discont = TRUE;
-      parse->priv->next_ts = parse->segment.last_stop;
+      parse->priv->next_ts = start_ts;
+      parse->priv->last_ts = GST_CLOCK_TIME_NONE;
       parse->priv->sync_offset = seekpos;
+      parse->priv->exact_position = accurate;
     }
 
     /* Start streaming thread if paused */
@@ -2584,22 +3343,41 @@ gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
   } else {
     GstEvent *new_event;
-    gint64 stop_pos;
+    GstBaseParseSeek *seek;
 
     /* The only thing we need to do in PUSH-mode is to send the
        seek event (in bytes) to upstream. Segment / flush handling happens
        in corresponding src event handlers */
     GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
-
-    /* already converted start, need same for stop */
-    dstformat = GST_FORMAT_BYTES;
-    if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.start,
-            &dstformat, &stop_pos))
-      goto convert_failed;
+    if (seekstop >= 0 && seekpos <= seekpos)
+      seekstop = seekpos;
     new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flush,
-        GST_SEEK_TYPE_SET, seekpos, stop_type, stop_pos);
+        GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
+
+    /* store segment info so its precise details can be reconstructed when
+     * receiving newsegment;
+     * this matters for all details when accurate seeking,
+     * is most useful to preserve NONE stop time otherwise */
+    seek = g_new0 (GstBaseParseSeek, 1);
+    seek->segment = seeksegment;
+    seek->accurate = accurate;
+    seek->offset = seekpos;
+    seek->start_ts = start_ts;
+    GST_OBJECT_LOCK (parse);
+    /* less optimal, but preserves order */
+    parse->priv->pending_seeks =
+        g_slist_append (parse->priv->pending_seeks, seek);
+    GST_OBJECT_UNLOCK (parse);
 
     res = gst_pad_push_event (parse->sinkpad, new_event);
+
+    if (!res) {
+      GST_OBJECT_LOCK (parse);
+      parse->priv->pending_seeks =
+          g_slist_remove (parse->priv->pending_seeks, seek);
+      GST_OBJECT_UNLOCK (parse);
+      g_free (seek);
+    }
   }
 
 done:
@@ -2642,12 +3420,18 @@ gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
 
   gst_event_parse_tag (event, &taglist);
 
-  if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp))
+  if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
+    GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
     parse->priv->post_min_bitrate = FALSE;
-  if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp))
+  }
+  if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
+    GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
     parse->priv->post_avg_bitrate = FALSE;
-  if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp))
+  }
+  if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
+    GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
     parse->priv->post_max_bitrate = FALSE;
+  }
 }
 
 /**