summaryrefslogtreecommitdiffstats
path: root/gst/id3demux/gstid3demux.c
blob: 6fec9dbdbcd1cc714d9997dc6162550e28e505d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: t; c-basic-offset: 2 -*- */
/* Copyright 2005 Jan Schmidt <thaytan@mad.scientist.com>
 * Copyright (C) 2003-2004 Benjamin Otte <otte@gnome.org>
 *
 * 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:element-id3demux
 * @short_description: reads tag information from ID3v1 and ID3v2 (<= 2.4.0) data blocks and outputs them as GStreamer tag messages and events.
 *
 * <refsect2>
 * <para>
 * id3demux accepts data streams with either (or both) ID3v2 regions at the start, or ID3v1 at the end. The mime type of the data between the tag blocks is detected using typefind functions, and the appropriate output mime type set on outgoing buffers. 
 * </para><para>
 * The element is only able to read ID3v1 tags from a seekable stream, because they are at the end of the stream. That is, when get_range mode is supported by the upstream elements. If get_range operation is available, id3demux makes it available downstream. This means that elements which require get_range mode, such as wavparse, can operate on files containing ID3 tag information.
 * </para>
 * <title>Example launch line</title>
 * <para>
 * <programlisting>
 * gst-launch filesrc location=file.mp3 ! id3demux ! fakesink -t
 * </programlisting>
 * This pipeline should read any available ID3 tag information and output it. The contents of the file inside the ID3 tag regions should be detected, and the appropriate mime type set on buffers produced from id3demux.
 * </para><para>
 * This id3demux element replaced an older element with the same name which relied on libid3tag from the MAD project.
 * </para>
 * </refsect2>
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gst/gst.h>
#include <gst/base/gsttypefindhelper.h>
#include <gst/gst-i18n-plugin.h>
#include <gst/tag/tag.h>
#include <string.h>

#include "gstid3demux.h"
#include "id3tags.h"

static const GstElementDetails gst_id3demux_details =
GST_ELEMENT_DETAILS ("ID3 tag demuxer",
    "Codec/Demuxer/Metadata",
    "Read and output ID3v1 and ID3v2 tags while demuxing the contents",
    "Jan Schmidt <thaytan@mad.scientist.com>");

enum
{
  ARG_0,
  ARG_PREFER_V1
};

/* Require at least 4kB of data before we attempt typefind. 
 * Seems a decent value based on test files
 * 40kB is massive overkill for the maximum, I think, but it 
 * doesn't do any harm */
#define ID3_TYPE_FIND_MIN_SIZE 4096
#define ID3_TYPE_FIND_MAX_SIZE 40960

GST_DEBUG_CATEGORY (id3demux_debug);
#define GST_CAT_DEFAULT (id3demux_debug)

static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("application/x-id3")
    );

static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
    GST_STATIC_CAPS ("ANY")
    );

static void gst_id3demux_class_init (GstID3DemuxClass * klass);
static void gst_id3demux_base_init (GstID3DemuxClass * klass);
static void gst_id3demux_init (GstID3Demux * id3demux);
static void gst_id3demux_dispose (GObject * object);

static void gst_id3demux_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
static void gst_id3demux_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);

static GstFlowReturn gst_id3demux_chain (GstPad * pad, GstBuffer * buf);
static gboolean gst_id3demux_sink_event (GstPad * pad, GstEvent * event);
static gboolean gst_id3demux_src_activate_pull (GstPad * pad, gboolean active);
static GstFlowReturn gst_id3demux_read_range (GstID3Demux * id3demux,
    guint64 offset, guint length, GstBuffer ** buffer);

static gboolean gst_id3demux_src_checkgetrange (GstPad * srcpad);
static GstFlowReturn gst_id3demux_src_getrange (GstPad * srcpad,
    guint64 offset, guint length, GstBuffer ** buffer);

static gboolean gst_id3demux_add_srcpad (GstID3Demux * id3demux,
    const GstCaps * new_caps);
static gboolean gst_id3demux_remove_srcpad (GstID3Demux * id3demux);

static gboolean gst_id3demux_srcpad_event (GstPad * pad, GstEvent * event);
static gboolean gst_id3demux_sink_activate (GstPad * sinkpad);
static GstStateChangeReturn gst_id3demux_change_state (GstElement * element,
    GstStateChange transition);
static gboolean gst_id3demux_pad_query (GstPad * pad, GstQuery * query);
static const GstQueryType *gst_id3demux_get_query_types (GstPad * pad);
static gboolean id3demux_get_upstream_size (GstID3Demux * id3demux);
static void gst_id3demux_send_tag_event (GstID3Demux * id3demux);

static GstElementClass *parent_class = NULL;

GType
gst_id3demux_get_type (void)
{
  static GType plugin_type = 0;

  if (!plugin_type) {
    static const GTypeInfo plugin_info = {
      sizeof (GstID3DemuxClass),
      (GBaseInitFunc) gst_id3demux_base_init,
      NULL,
      (GClassInitFunc) gst_id3demux_class_init,
      NULL,
      NULL,
      sizeof (GstID3Demux),
      0,
      (GInstanceInitFunc) gst_id3demux_init,
    };
    plugin_type = g_type_register_static (GST_TYPE_ELEMENT,
        "GstID3Demux", &plugin_info, 0);
  }
  return plugin_type;
}

static void
gst_id3demux_base_init (GstID3DemuxClass * klass)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (klass);

  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&src_factory));
  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&sink_factory));
  gst_element_class_set_details (element_class, &gst_id3demux_details);
}

static void
gst_id3demux_class_init (GstID3DemuxClass * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;

  gobject_class = (GObjectClass *) klass;
  gstelement_class = (GstElementClass *) klass;

  parent_class = g_type_class_peek_parent (klass);

  gobject_class->dispose = gst_id3demux_dispose;

  gobject_class->set_property = gst_id3demux_set_property;
  gobject_class->get_property = gst_id3demux_get_property;

  gstelement_class->change_state = gst_id3demux_change_state;

  g_object_class_install_property (gobject_class, ARG_PREFER_V1,
      g_param_spec_boolean ("prefer-v1", "Prefer version 1 tag",
          "Prefer tags from ID3v1 tag at end of file when both ID3v1 "
          "and ID3v2 tags are present", FALSE,
          G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
}

static void
gst_id3demux_reset (GstID3Demux * id3demux)
{
  GstBuffer **buffer_p = &id3demux->collect;
  GstCaps **caps_p = &id3demux->src_caps;

  id3demux->strip_start = 0;
  id3demux->strip_end = 0;
  id3demux->upstream_size = -1;
  id3demux->state = GST_ID3DEMUX_READID3V2;
  id3demux->send_tag_event = FALSE;

  gst_buffer_replace (buffer_p, NULL);
  gst_caps_replace (caps_p, NULL);

  gst_id3demux_remove_srcpad (id3demux);

  if (id3demux->event_tags) {
    gst_tag_list_free (id3demux->event_tags);
    id3demux->event_tags = NULL;
  }
  if (id3demux->parsed_tags) {
    gst_tag_list_free (id3demux->parsed_tags);
    id3demux->parsed_tags = NULL;
  }

}

static void
gst_id3demux_init (GstID3Demux * id3demux)
{
  GstElementClass *klass = GST_ELEMENT_GET_CLASS (id3demux);

  id3demux->sinkpad =
      gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
          "sink"), "sink");
  gst_pad_set_activate_function (id3demux->sinkpad,
      GST_DEBUG_FUNCPTR (gst_id3demux_sink_activate));
  gst_pad_set_event_function (id3demux->sinkpad,
      GST_DEBUG_FUNCPTR (gst_id3demux_sink_event));
  gst_pad_set_chain_function (id3demux->sinkpad,
      GST_DEBUG_FUNCPTR (gst_id3demux_chain));
  gst_element_add_pad (GST_ELEMENT (id3demux), id3demux->sinkpad);

  id3demux->prefer_v1 = FALSE;
  gst_id3demux_reset (id3demux);
}

static void
gst_id3demux_dispose (GObject * object)
{
  GstID3Demux *id3demux = GST_ID3DEMUX (object);

  gst_id3demux_reset (id3demux);

  G_OBJECT_CLASS (parent_class)->dispose (object);
}

static gboolean
gst_id3demux_add_srcpad (GstID3Demux * id3demux, const GstCaps * new_caps)
{
  if (id3demux->src_caps == NULL ||
      !gst_caps_is_equal (new_caps, id3demux->src_caps)) {

    gst_caps_replace (&(id3demux->src_caps), (GstCaps *) new_caps);
    if (id3demux->srcpad != NULL) {
      GST_DEBUG_OBJECT (id3demux, "Changing src pad caps to %" GST_PTR_FORMAT,
          id3demux->src_caps);

      gst_pad_set_caps (id3demux->srcpad, id3demux->src_caps);
    }
  } else {
    /* caps didn't change */
  }

  if (id3demux->srcpad == NULL) {
    id3demux->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
    g_return_val_if_fail (id3demux->srcpad != NULL, FALSE);

    gst_pad_set_query_type_function (id3demux->srcpad,
        GST_DEBUG_FUNCPTR (gst_id3demux_get_query_types));
    gst_pad_set_query_function (id3demux->srcpad,
        GST_DEBUG_FUNCPTR (gst_id3demux_pad_query));
    gst_pad_set_event_function (id3demux->srcpad,
        GST_DEBUG_FUNCPTR (gst_id3demux_srcpad_event));
    gst_pad_set_activatepull_function (id3demux->srcpad,
        GST_DEBUG_FUNCPTR (gst_id3demux_src_activate_pull));
    gst_pad_set_checkgetrange_function (id3demux->srcpad,
        GST_DEBUG_FUNCPTR (gst_id3demux_src_checkgetrange));
    gst_pad_set_getrange_function (id3demux->srcpad,
        GST_DEBUG_FUNCPTR (gst_id3demux_src_getrange));

    gst_pad_use_fixed_caps (id3demux->srcpad);

    if (id3demux->src_caps)
      gst_pad_set_caps (id3demux->srcpad, id3demux->src_caps);

    GST_DEBUG_OBJECT (id3demux, "Adding src pad with caps %" GST_PTR_FORMAT,
        id3demux->src_caps);

    gst_object_ref (id3demux->srcpad);
    gst_pad_set_active (id3demux->srcpad, TRUE);
    if (!(gst_element_add_pad (GST_ELEMENT (id3demux), id3demux->srcpad)))
      return FALSE;
    gst_element_no_more_pads (GST_ELEMENT (id3demux));
  }

  return TRUE;
}

static gboolean
gst_id3demux_remove_srcpad (GstID3Demux * id3demux)
{
  gboolean res = TRUE;

  if (id3demux->srcpad != NULL) {
    GST_DEBUG_OBJECT (id3demux, "Removing src pad");
    res = gst_element_remove_pad (GST_ELEMENT (id3demux), id3demux->srcpad);
    g_return_val_if_fail (res != FALSE, FALSE);
    gst_object_unref (id3demux->srcpad);
    id3demux->srcpad = NULL;
  }

  return res;
};

/* will return FALSE if buffer is beyond end of data; will return TRUE
 * if buffer was trimmed successfully or didn't need trimming, but may
 * also return TRUE and set *buf_ref to NULL if the buffer was before
 * the start of the data */
static gboolean
gst_id3demux_trim_buffer (GstID3Demux * id3demux, GstBuffer ** buf_ref)
{
  GstBuffer *buf = *buf_ref;

  guint trim_start = 0;
  guint out_size = GST_BUFFER_SIZE (buf);
  guint64 out_offset = GST_BUFFER_OFFSET (buf);
  gboolean need_sub = FALSE;

  /* Adjust offset and length */
  if (!GST_BUFFER_OFFSET_IS_VALID (buf)) {
    /* Can't change anything without an offset */
    return TRUE;
  }

  /* If the buffer crosses the ID3v1 tag at the end of file, trim it */
  if (id3demux->strip_end > 0) {
    if (id3demux_get_upstream_size (id3demux)) {
      guint64 v1tag_offset = id3demux->upstream_size - id3demux->strip_end;

      if (out_offset >= v1tag_offset) {
        GST_DEBUG_OBJECT (id3demux, "Buffer is past the end of the data");
        goto no_out_buffer_end;
      }

      if (out_offset + out_size > v1tag_offset) {
        out_size = v1tag_offset - out_offset;
        need_sub = TRUE;
      }
    }
  }

  if (id3demux->strip_start > 0) {
    /* If the buffer crosses the ID3v2 tag at the start of file, trim it */
    if (out_offset <= id3demux->strip_start) {
      if (out_offset + out_size <= id3demux->strip_start) {
        GST_DEBUG_OBJECT (id3demux, "Buffer is before the start of the data");
        goto no_out_buffer_start;
      }

      trim_start = id3demux->strip_start - out_offset;
      out_size -= trim_start;
      out_offset = 0;
    } else {
      out_offset -= id3demux->strip_start;
    }
    need_sub = TRUE;
  }

  g_assert (out_size > 0);

  if (need_sub == TRUE) {
    if (out_size != GST_BUFFER_SIZE (buf) || !gst_buffer_is_writable (buf)) {
      GstBuffer *sub;

      GST_DEBUG_OBJECT (id3demux, "Sub-buffering to trim size %d offset %"
          G_GINT64_FORMAT " to %d offset %" G_GINT64_FORMAT,
          GST_BUFFER_SIZE (buf), GST_BUFFER_OFFSET (buf), out_size, out_offset);

      sub = gst_buffer_create_sub (buf, trim_start, out_size);
      g_return_val_if_fail (sub != NULL, FALSE);
      gst_buffer_unref (buf);
      *buf_ref = buf = sub;
    } else {
      GST_DEBUG_OBJECT (id3demux, "Adjusting buffer from size %d offset %"
          G_GINT64_FORMAT " to %d offset %" G_GINT64_FORMAT,
          GST_BUFFER_SIZE (buf), GST_BUFFER_OFFSET (buf), out_size, out_offset);
    }

    GST_BUFFER_OFFSET (buf) = out_offset;
    GST_BUFFER_OFFSET_END (buf) = out_offset + out_size;
    gst_buffer_set_caps (buf, id3demux->src_caps);
  }

  return TRUE;

no_out_buffer_end:
  {
    gst_buffer_unref (buf);
    *buf_ref = NULL;
    return FALSE;
  }
no_out_buffer_start:
  {
    gst_buffer_unref (buf);
    *buf_ref = NULL;
    return TRUE;
  }
}

static GstFlowReturn
gst_id3demux_chain (GstPad * pad, GstBuffer * buf)
{
  GstID3Demux *id3demux;

  id3demux = GST_ID3DEMUX (GST_PAD_PARENT (pad));
  g_return_val_if_fail (GST_IS_ID3DEMUX (id3demux), GST_FLOW_ERROR);

  if (id3demux->collect == NULL) {
    id3demux->collect = buf;
  } else {
    id3demux->collect = gst_buffer_join (id3demux->collect, buf);
  }
  buf = NULL;

  switch (id3demux->state) {
    case GST_ID3DEMUX_READID3V2:
      if (GST_BUFFER_SIZE (id3demux->collect) < 3)
        break;                  /* Go get more data first */

      /* need to set offset of first buffer to 0 or trimming won't work */
      if (!GST_BUFFER_OFFSET_IS_VALID (id3demux->collect) &&
          memcmp (GST_BUFFER_DATA (id3demux->collect), "ID3", 3) == 0) {
        GST_WARNING_OBJECT (id3demux, "Fixing up first buffer without offset");
        id3demux->collect =
            gst_buffer_make_metadata_writable (id3demux->collect);
        GST_BUFFER_OFFSET (id3demux->collect) = 0;
      }

      /* If we receive a buffer that's from the middle of the file, 
       * we can't read tags so move to typefinding */
      if (!GST_BUFFER_OFFSET_IS_VALID (id3demux->collect) ||
          GST_BUFFER_OFFSET (id3demux->collect) != 0) {
        GST_DEBUG_OBJECT (id3demux,
            "Received buffer with non-zero offset %" G_GINT64_FORMAT
            ". Can't read tags", GST_BUFFER_OFFSET (id3demux->collect));
      } else {
        ID3TagsResult tag_result;

        tag_result = id3demux_read_id3v2_tag (id3demux->collect,
            &id3demux->strip_start, &id3demux->parsed_tags);
        if (tag_result == ID3TAGS_MORE_DATA)
          break;                /* Go get more data and try again */
        else if (tag_result == ID3TAGS_BROKEN_TAG)
          GST_WARNING_OBJECT (id3demux,
              "Ignoring broken ID3v2 tag of size %d", id3demux->strip_start);
        else
          GST_DEBUG_OBJECT (id3demux, "Found an ID3v2 tag of size %d\n",
              id3demux->strip_start);

        id3demux->send_tag_event = TRUE;
      }
      id3demux->state = GST_ID3DEMUX_TYPEFINDING;

      /* Fall-through */
    case GST_ID3DEMUX_TYPEFINDING:{
      GstTypeFindProbability probability = 0;
      GstBuffer *typefind_buf = NULL;
      GstCaps *caps;

      if (GST_BUFFER_SIZE (id3demux->collect) <
          ID3_TYPE_FIND_MIN_SIZE + id3demux->strip_start)
        break;                  /* Go get more data first */

      GST_DEBUG_OBJECT (id3demux, "Typefinding with size %d",
          GST_BUFFER_SIZE (id3demux->collect));

      /* Trim the buffer and adjust offset for typefinding */
      typefind_buf = id3demux->collect;
      gst_buffer_ref (typefind_buf);
      if (!gst_id3demux_trim_buffer (id3demux, &typefind_buf))
        return GST_FLOW_UNEXPECTED;

      if (typefind_buf == NULL)
        break;                  /* Still need more data */

      caps = gst_type_find_helper_for_buffer (GST_OBJECT (id3demux),
          typefind_buf, &probability);

      if (caps == NULL) {
        if (GST_BUFFER_SIZE (typefind_buf) < ID3_TYPE_FIND_MAX_SIZE) {
          /* Just break for more data */
          gst_buffer_unref (typefind_buf);
          return GST_FLOW_OK;
        }

        /* We failed typefind */
        GST_ELEMENT_ERROR (id3demux, STREAM, TYPE_NOT_FOUND, (NULL),
            ("Could not detect type for contents within an ID3 tag"));
        gst_buffer_unref (typefind_buf);
        gst_buffer_unref (id3demux->collect);
        id3demux->collect = NULL;
        return GST_FLOW_ERROR;
      }

      GST_DEBUG_OBJECT (id3demux, "Found type %" GST_PTR_FORMAT " with a "
          "probability of %u, buf size was %u", caps, probability,
          GST_BUFFER_SIZE (typefind_buf));

      gst_buffer_unref (typefind_buf);

      if (!gst_id3demux_add_srcpad (id3demux, caps)) {
        GST_DEBUG_OBJECT (id3demux, "Failed to add srcpad");
        gst_caps_unref (caps);
        goto error;
      }
      gst_caps_unref (caps);

      /* Move onto streaming and fall-through to push out existing
       * data */
      id3demux->state = GST_ID3DEMUX_STREAMING;

      /* Now that typefinding is complete, post the
       * tags message */
      if (id3demux->parsed_tags != NULL) {
        gst_element_post_message (GST_ELEMENT (id3demux),
            gst_message_new_tag (GST_OBJECT (id3demux),
                gst_tag_list_copy (id3demux->parsed_tags)));
      }
      /* fall-through */
    }
    case GST_ID3DEMUX_STREAMING:{
      GstBuffer *outbuf = NULL;

      if (id3demux->send_tag_event) {
        gst_id3demux_send_tag_event (id3demux);
        id3demux->send_tag_event = FALSE;
      }

      /* Trim the buffer and adjust offset */
      if (id3demux->collect) {
        outbuf = id3demux->collect;
        id3demux->collect = NULL;
        if (!gst_id3demux_trim_buffer (id3demux, &outbuf))
          return GST_FLOW_UNEXPECTED;
      }
      if (outbuf) {
        if (G_UNLIKELY (id3demux->srcpad == NULL)) {
          gst_buffer_unref (outbuf);
          return GST_FLOW_ERROR;
        }

        GST_DEBUG_OBJECT (id3demux, "Pushing buffer %p", outbuf);

        /* Ensure the caps are set correctly */
        outbuf = gst_buffer_make_metadata_writable (outbuf);
        gst_buffer_set_caps (outbuf, GST_PAD_CAPS (id3demux->srcpad));

        return gst_pad_push (id3demux->srcpad, outbuf);
      }
    }
  }
  return GST_FLOW_OK;

error:
  GST_DEBUG_OBJECT (id3demux, "error in chain function");

  return GST_FLOW_ERROR;
}

static gboolean
gst_id3demux_sink_event (GstPad * pad, GstEvent * event)
{
  GstID3Demux *demux;
  gboolean ret;

  demux = GST_ID3DEMUX (gst_pad_get_parent (pad));

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_EOS:
      if (demux->srcpad == NULL) {
        GST_WARNING_OBJECT (demux, "EOS before we found a type");
        GST_ELEMENT_ERROR (demux, STREAM, TYPE_NOT_FOUND, (NULL), (NULL));
      }
      ret = gst_pad_event_default (pad, event);
      break;
    default:
      ret = gst_pad_event_default (pad, event);
      break;
  }

  gst_object_unref (demux);
  return ret;
}


static void
gst_id3demux_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstID3Demux *id3demux;

  g_return_if_fail (GST_IS_ID3DEMUX (object));
  id3demux = GST_ID3DEMUX (object);

  switch (prop_id) {
    case ARG_PREFER_V1:
      id3demux->prefer_v1 = g_value_get_boolean (value);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_id3demux_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  GstID3Demux *id3demux;

  g_return_if_fail (GST_IS_ID3DEMUX (object));
  id3demux = GST_ID3DEMUX (object);

  switch (prop_id) {
    case ARG_PREFER_V1:
      g_value_set_boolean (value, id3demux->prefer_v1);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static gboolean
id3demux_get_upstream_size (GstID3Demux * id3demux)
{
  GstFormat format;
  gint64 result;

  /* Short-cut if we already queried upstream */
  if (id3demux->upstream_size > 0)
    return TRUE;

  format = GST_FORMAT_BYTES;
  if (!gst_pad_query_peer_duration (id3demux->sinkpad, &format, &result) ||
      result < 0) {
    return FALSE;
  }

  id3demux->upstream_size = result;
  return TRUE;
}

static gboolean
gst_id3demux_srcpad_event (GstPad * pad, GstEvent * event)
{
  gboolean res = FALSE;
  GstID3Demux *id3demux = GST_ID3DEMUX (GST_PAD_PARENT (pad));

  /* Handle SEEK events, with adjusted byte offsets and sizes. */

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_SEEK:
    {
      gdouble rate;
      GstFormat format;
      GstSeekType cur_type, stop_type;
      GstSeekFlags flags;
      gint64 cur, stop;

      gst_event_parse_seek (event, &rate, &format, &flags,
          &cur_type, &cur, &stop_type, &stop);

      if (format == GST_FORMAT_BYTES &&
          id3demux->state == GST_ID3DEMUX_STREAMING &&
          gst_pad_is_linked (id3demux->sinkpad)) {
        GstEvent *upstream;

        switch (cur_type) {
          case GST_SEEK_TYPE_SET:
            if (cur == -1)
              cur = 0;
            cur += id3demux->strip_start;
            break;
          case GST_SEEK_TYPE_CUR:
            break;
          case GST_SEEK_TYPE_END:
            /* Adjust the seek to be relative to the start of any ID3v1 tag */
            if (cur > 0)
              cur = 0;
            cur -= id3demux->strip_end;
            break;
          default:
            g_assert_not_reached ();
            break;
        }
        switch (stop_type) {
          case GST_SEEK_TYPE_SET:
            if (stop != -1) {
              /* -1 means the end of the file, pass it upstream intact */
              stop += id3demux->strip_start;
            }
            break;
          case GST_SEEK_TYPE_CUR:
            break;
          case GST_SEEK_TYPE_END:
            /* Adjust the seek to be relative to the start of any ID3v1 tag */
            if (stop > 0)
              stop = 0;
            stop -= id3demux->strip_end;
            break;
          default:
            break;
        }
        upstream = gst_event_new_seek (rate, format, flags,
            cur_type, cur, stop_type, stop);
        res = gst_pad_push_event (id3demux->sinkpad, upstream);
      }
      break;
    }
    default:
      break;
  }

  gst_event_unref (event);
  return res;
}

/* Read and interpret any ID3v1 tag when activating in pull_range */
static gboolean
gst_id3demux_read_id3v1 (GstID3Demux * id3demux, GstTagList ** tags)
{
  GstBuffer *buffer = NULL;
  gboolean res = FALSE;
  ID3TagsResult tag_res;
  GstFlowReturn flow_ret;
  guint64 id3v1_offset;

  if (id3demux->upstream_size < ID3V1_TAG_SIZE)
    return TRUE;
  id3v1_offset = id3demux->upstream_size - ID3V1_TAG_SIZE;

  flow_ret = gst_pad_pull_range (id3demux->sinkpad, id3v1_offset,
      ID3V1_TAG_SIZE, &buffer);
  if (flow_ret != GST_FLOW_OK) {
    GST_DEBUG_OBJECT (id3demux,
        "Could not read data from start of file ret=%d", flow_ret);
    goto beach;
  }

  if (GST_BUFFER_SIZE (buffer) != ID3V1_TAG_SIZE) {
    GST_DEBUG_OBJECT (id3demux,
        "Only managed to read %u bytes from file - not an ID3 file",
        GST_BUFFER_SIZE (buffer));
    goto beach;
  }

  tag_res = id3demux_read_id3v1_tag (buffer, &id3demux->strip_end, tags);
  if (tag_res == ID3TAGS_READ_TAG) {
    GST_DEBUG_OBJECT (id3demux,
        "Read ID3v1 tag - trimming %d bytes from end of file",
        id3demux->strip_end);
    res = TRUE;
  } else if (tag_res == ID3TAGS_BROKEN_TAG) {
    GST_WARNING_OBJECT (id3demux, "Ignoring broken ID3v1 tag");
    res = TRUE;
  }
beach:
  if (buffer)
    gst_buffer_unref (buffer);
  return res;
}

/* Read and interpret any ID3v2 tag when activating in pull_range */
static gboolean
gst_id3demux_read_id3v2 (GstID3Demux * id3demux, GstTagList ** tags)
{
  GstBuffer *buffer = NULL;
  gboolean res = FALSE;
  ID3TagsResult tag_res;
  GstFlowReturn flow_ret;

  /* Handle ID3V2 tag. Try with 4kB to start with */
  flow_ret = gst_pad_pull_range (id3demux->sinkpad, 0, 4096, &buffer);
  if (flow_ret != GST_FLOW_OK) {
    GST_DEBUG_OBJECT (id3demux,
        "Could not read data from start of file ret=%d", flow_ret);
    goto beach;
  }

  if (GST_BUFFER_SIZE (buffer) < ID3V2_HDR_SIZE) {
    GST_DEBUG_OBJECT (id3demux,
        "Only managed to read %u bytes from file - not an ID3 file",
        GST_BUFFER_SIZE (buffer));
    goto beach;
  }

  tag_res = id3demux_read_id3v2_tag (buffer, &id3demux->strip_start, tags);
  if (tag_res == ID3TAGS_MORE_DATA) {
    /* Need more data to interpret the tag */
    if (buffer) {
      gst_buffer_unref (buffer);
      buffer = NULL;
    }
    g_assert (id3demux->strip_start > ID3V2_HDR_SIZE);

    GST_DEBUG_OBJECT (id3demux, "Reading %u bytes to decode ID3v2",
        id3demux->strip_start);
    flow_ret = gst_pad_pull_range (id3demux->sinkpad, 0, id3demux->strip_start,
        &buffer);
    if (flow_ret != GST_FLOW_OK) {
      GST_DEBUG_OBJECT (id3demux,
          "Could not read data from start of file ret=%d", flow_ret);
      goto beach;
    }
    tag_res = id3demux_read_id3v2_tag (buffer, &id3demux->strip_start, tags);
  }

  if (tag_res == ID3TAGS_READ_TAG) {
    res = TRUE;
    GST_DEBUG_OBJECT (id3demux, "Read ID3v2 tag of size %d",
        id3demux->strip_start);
  } else if (tag_res == ID3TAGS_BROKEN_TAG) {
    res = TRUE;
    GST_WARNING_OBJECT (id3demux, "Ignoring broken ID3v2 tag of size %d",
        id3demux->strip_start);
  }
beach:
  if (buffer)
    gst_buffer_unref (buffer);
  return res;
}

/* This function operates similarly to gst_type_find_element_activate
 * in the typefind element
 * 1. try to activate in pull mode. if not, switch to push and succeed.
 * 2. try to read tags in pull mode
 * 3. typefind the contents
 * 4. deactivate pull mode.
 * 5. if we didn't find any caps, fail.
 * 6. Add the srcpad
 * 7. if the sink pad is activated, we are in pull mode. succeed.
 *    otherwise activate both pads in push mode and succeed.
 */
static gboolean
gst_id3demux_sink_activate (GstPad * sinkpad)
{
  GstTypeFindProbability probability = 0;
  GstID3Demux *id3demux = GST_ID3DEMUX (GST_PAD_PARENT (sinkpad));
  gboolean ret = FALSE;
  GstCaps *caps = NULL;

  /* 1: */
  /* If we can activate pull_range upstream, then read any ID3v1 and ID3v2
   * tags, otherwise activate in push mode and the chain function will 
   * collect buffers, read the ID3v2 tag and output a buffer to end
   * preroll.
   */
  if (!gst_pad_check_pull_range (sinkpad) ||
      !gst_pad_activate_pull (sinkpad, TRUE)) {
    GST_DEBUG_OBJECT (id3demux,
        "No pull mode. Changing to push, but won't be able to read ID3v1 tags");
    id3demux->state = GST_ID3DEMUX_READID3V2;
    return gst_pad_activate_push (sinkpad, TRUE);
  }

  /* Look for tags at start and end of file */
  GST_DEBUG_OBJECT (id3demux, "Activated pull mode. Looking for tags");
  if (!id3demux_get_upstream_size (id3demux))
    return FALSE;

  id3demux->strip_start = 0;
  id3demux->strip_end = 0;


  if (id3demux->prefer_v1) {
    if (!gst_id3demux_read_id3v2 (id3demux, &(id3demux->parsed_tags)))
      return FALSE;
    if (!gst_id3demux_read_id3v1 (id3demux, &(id3demux->parsed_tags)))
      return FALSE;
  } else {
    if (!gst_id3demux_read_id3v1 (id3demux, &(id3demux->parsed_tags)))
      return FALSE;
    if (!gst_id3demux_read_id3v2 (id3demux, &(id3demux->parsed_tags)))
      return FALSE;
  }
  if (id3demux->parsed_tags != NULL) {
    id3demux->send_tag_event = TRUE;
  }

  /* 3 - Do typefinding on data */
  caps = gst_type_find_helper_get_range (GST_OBJECT (id3demux),
      (GstTypeFindHelperGetRangeFunction) gst_id3demux_read_range,
      id3demux->upstream_size - id3demux->strip_start - id3demux->strip_end,
      &probability);

  GST_DEBUG_OBJECT (id3demux, "Found type %" GST_PTR_FORMAT " with a "
      "probability of %u", caps, probability);

  /* 4 - Deactivate pull mode */
  if (!gst_pad_activate_pull (sinkpad, FALSE)) {
    if (caps)
      gst_caps_unref (caps);
    GST_DEBUG_OBJECT (id3demux,
        "Could not deactivate sinkpad after reading tags");
    return FALSE;
  }

  /* 5 - If we didn't find the caps, fail */
  if (caps == NULL) {
    GST_ELEMENT_ERROR (id3demux, STREAM, TYPE_NOT_FOUND, (NULL),
        ("Could not detect type for contents within an ID3 tag"));
    goto done_activate;
  }

  /* Now that we've finished typefinding, post tag message on bus */
  if (id3demux->parsed_tags != NULL) {
    gst_element_post_message (GST_ELEMENT (id3demux),
        gst_message_new_tag (GST_OBJECT (id3demux),
            gst_tag_list_copy (id3demux->parsed_tags)));
  }

  /* tag reading and typefinding were already done, don't do them again in
     the chain function if we end up in push mode */
  id3demux->state = GST_ID3DEMUX_STREAMING;

  /* 6 Add the srcpad for output now we know caps. */
  if (!gst_id3demux_add_srcpad (id3demux, caps)) {
    GST_DEBUG_OBJECT (id3demux, "Could not add source pad");
    goto done_activate;
  }

  /* 7 - if the sinkpad is active, it was done by downstream so we're 
   * done, otherwise switch to push */
  ret = TRUE;
  if (!gst_pad_is_active (sinkpad)) {
    ret = gst_pad_activate_push (id3demux->srcpad, TRUE);
    ret &= gst_pad_activate_push (sinkpad, TRUE);
  }

done_activate:

  if (caps)
    gst_caps_unref (caps);

  return ret;
}

static gboolean
gst_id3demux_src_activate_pull (GstPad * pad, gboolean active)
{
  GstID3Demux *id3demux = GST_ID3DEMUX (GST_PAD_PARENT (pad));

  return gst_pad_activate_pull (id3demux->sinkpad, active);
}

static gboolean
gst_id3demux_src_checkgetrange (GstPad * srcpad)
{
  GstID3Demux *id3demux = GST_ID3DEMUX (GST_PAD_PARENT (srcpad));

  return gst_pad_check_pull_range (id3demux->sinkpad);
}

static GstFlowReturn
gst_id3demux_read_range (GstID3Demux * id3demux,
    guint64 offset, guint length, GstBuffer ** buffer)
{
  GstFlowReturn ret;
  guint64 in_offset;
  guint in_length;

  g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);

  /* Adjust offset and length of the request to trim off ID3 information. 
   * For the returned buffer, adjust the output offset to match what downstream
   * should see */
  in_offset = offset + id3demux->strip_start;

  if (!id3demux_get_upstream_size (id3demux))
    return GST_FLOW_ERROR;

  if (in_offset + length >= id3demux->upstream_size - id3demux->strip_end) {
    if (in_offset + id3demux->strip_end >= id3demux->upstream_size)
      return GST_FLOW_UNEXPECTED;
    in_length = id3demux->upstream_size - id3demux->strip_end - in_offset;
  } else {
    in_length = length;
  }

  ret = gst_pad_pull_range (id3demux->sinkpad, in_offset, in_length, buffer);
  if (ret == GST_FLOW_OK && *buffer) {
    if (!gst_id3demux_trim_buffer (id3demux, buffer))
      goto read_beyond_end;

    /* this should only happen in streaming mode */
    g_assert (*buffer != NULL);

    gst_buffer_set_caps (*buffer, id3demux->src_caps);
  }

  return ret;

read_beyond_end:
  {
    GST_DEBUG_OBJECT (id3demux, "attempted read beyond end of file");
    if (*buffer != NULL) {
      gst_buffer_unref (buffer);
      *buffer = NULL;
    }
    return GST_FLOW_UNEXPECTED;
  }
}

static GstFlowReturn
gst_id3demux_src_getrange (GstPad * srcpad,
    guint64 offset, guint length, GstBuffer ** buffer)
{
  GstID3Demux *id3demux = GST_ID3DEMUX (GST_PAD_PARENT (srcpad));

  if (id3demux->send_tag_event) {
    gst_id3demux_send_tag_event (id3demux);
    id3demux->send_tag_event = FALSE;
  }
  return gst_id3demux_read_range (id3demux, offset, length, buffer);
}

static GstStateChangeReturn
gst_id3demux_change_state (GstElement * element, GstStateChange transition)
{
  GstStateChangeReturn ret;
  GstID3Demux *id3demux = GST_ID3DEMUX (element);

  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);

  switch (transition) {
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      gst_id3demux_reset (id3demux);
      break;
    default:
      break;
  }
  return ret;
}

static gboolean
gst_id3demux_pad_query (GstPad * pad, GstQuery * query)
{
  /* For a position or duration query, adjust the returned
   * bytes to strip off the id3v1 and id3v2 areas */

  GstID3Demux *id3demux = GST_ID3DEMUX (GST_PAD_PARENT (pad));
  GstPad *peer = NULL;
  GstFormat format;
  gint64 result;

  if ((peer = gst_pad_get_peer (id3demux->sinkpad)) == NULL)
    return FALSE;

  if (!gst_pad_query (peer, query)) {
    gst_object_unref (peer);
    return FALSE;
  }

  gst_object_unref (peer);

  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_POSITION:
    {
      gst_query_parse_position (query, &format, &result);
      if (format == GST_FORMAT_BYTES) {
        result -= id3demux->strip_start;
        gst_query_set_position (query, format, result);
      }
      break;
    }
    case GST_QUERY_DURATION:
    {
      gst_query_parse_duration (query, &format, &result);
      if (format == GST_FORMAT_BYTES) {
        result -= id3demux->strip_start + id3demux->strip_end;
        gst_query_set_duration (query, format, result);
      }
      break;
    }
    default:
      break;
  }

  return TRUE;
}

static const GstQueryType *
gst_id3demux_get_query_types (GstPad * pad)
{
  static const GstQueryType types[] = {
    GST_QUERY_POSITION,
    GST_QUERY_DURATION,
    0
  };

  return types;
}

static void
gst_id3demux_send_tag_event (GstID3Demux * id3demux)
{
  /* FIXME: what's the correct merge mode? Docs need to tell... */
  GstTagList *merged = gst_tag_list_merge (id3demux->event_tags,
      id3demux->parsed_tags, GST_TAG_MERGE_KEEP);

  if (merged) {
    GstEvent *event = gst_event_new_tag (merged);

    GST_EVENT_TIMESTAMP (event) = 0;
    GST_DEBUG_OBJECT (id3demux, "Sending tag event on src pad");
    gst_pad_push_event (id3demux->srcpad, event);
  }
}

static gboolean
plugin_init (GstPlugin * plugin)
{
  GST_DEBUG_CATEGORY_INIT (id3demux_debug, "id3demux", 0,
      "GStreamer ID3 tag demuxer");

  gst_tag_register_musicbrainz_tags ();

  /* ensure private tag is registered */
  gst_tag_register (GST_ID3_DEMUX_TAG_ID3V2_FRAME, GST_TAG_FLAG_META,
      GST_TYPE_BUFFER, "ID3v2 frame", "unparsed id3v2 tag frame",
      gst_tag_merge_use_first);

  return gst_element_register (plugin, "id3demux",
      GST_RANK_PRIMARY, GST_TYPE_ID3DEMUX);
}

GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    "id3demux",
    "Demux ID3v1 and ID3v2 tags from a file",
    plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)