Tizen 2.0 Release
[framework/multimedia/gst-plugins-good0.10.git] / gst / audioparsers / gstamrparse.c
1 /* GStreamer Adaptive Multi-Rate parser plugin
2  * Copyright (C) 2006 Edgard Lima <edgard.lima@indt.org.br>
3  * Copyright (C) 2008 Nokia Corporation. All rights reserved.
4  *
5  * Contact: Stefan Kost <stefan.kost@nokia.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /**
24  * SECTION:element-amrparse
25  * @short_description: AMR parser
26  * @see_also: #GstAmrnbDec, #GstAmrnbEnc
27  *
28  * This is an AMR parser capable of handling both narrow-band and wideband
29  * formats.
30  *
31  * <refsect2>
32  * <title>Example launch line</title>
33  * |[
34  * gst-launch filesrc location=abc.amr ! amrparse ! amrdec ! audioresample ! audioconvert ! alsasink
35  * ]|
36  * </refsect2>
37  */
38
39 #ifdef HAVE_CONFIG_H
40 #include "config.h"
41 #endif
42
43 #include <string.h>
44
45 #include "gstamrparse.h"
46
47
48 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
49     GST_PAD_SRC,
50     GST_PAD_ALWAYS,
51     GST_STATIC_CAPS ("audio/AMR, " "rate = (int) 8000, " "channels = (int) 1;"
52         "audio/AMR-WB, " "rate = (int) 16000, " "channels = (int) 1;")
53     );
54
55 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
56     GST_PAD_SINK,
57     GST_PAD_ALWAYS,
58     GST_STATIC_CAPS ("audio/x-amr-nb-sh; audio/x-amr-wb-sh"));
59
60 GST_DEBUG_CATEGORY_STATIC (amrparse_debug);
61 #define GST_CAT_DEFAULT amrparse_debug
62
63 static const gint block_size_nb[16] =
64     { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0 };
65
66 static const gint block_size_wb[16] =
67     { 17, 23, 32, 36, 40, 46, 50, 58, 60, 5, -1, -1, -1, -1, 0, 0 };
68
69 /* AMR has a "hardcoded" framerate of 50fps */
70 #define AMR_FRAMES_PER_SECOND 50
71 #define AMR_FRAME_DURATION (GST_SECOND/AMR_FRAMES_PER_SECOND)
72 #define AMR_MIME_HEADER_SIZE 9
73
74 static gboolean gst_amr_parse_start (GstBaseParse * parse);
75 static gboolean gst_amr_parse_stop (GstBaseParse * parse);
76
77 static gboolean gst_amr_parse_sink_setcaps (GstBaseParse * parse,
78     GstCaps * caps);
79 static GstCaps *gst_amr_parse_sink_getcaps (GstBaseParse * parse);
80
81 static gboolean gst_amr_parse_check_valid_frame (GstBaseParse * parse,
82     GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
83
84 static GstFlowReturn gst_amr_parse_parse_frame (GstBaseParse * parse,
85     GstBaseParseFrame * frame);
86
87 #ifdef GST_EXT_AMRPARSER_MODIFICATION /* make full amr index table when seek */
88 static gboolean gst_amr_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event);
89
90 #define AMR_MAX_PULL_RANGE_BUF (5 * 1024 * 1024) /* 5 mbyte */
91 #endif
92
93 #define _do_init(bla) \
94     GST_DEBUG_CATEGORY_INIT (amrparse_debug, "amrparse", 0, \
95                              "AMR-NB audio stream parser");
96
97 GST_BOILERPLATE_FULL (GstAmrParse, gst_amr_parse, GstBaseParse,
98     GST_TYPE_BASE_PARSE, _do_init);
99
100 /**
101  * gst_amr_parse_base_init:
102  * @klass: #GstElementClass.
103  *
104  */
105 static void
106 gst_amr_parse_base_init (gpointer klass)
107 {
108   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
109
110   gst_element_class_add_static_pad_template (element_class,
111       &sink_template);
112   gst_element_class_add_static_pad_template (element_class, &src_template);
113
114   gst_element_class_set_details_simple (element_class,
115       "AMR audio stream parser", "Codec/Parser/Audio",
116       "Adaptive Multi-Rate audio parser",
117       "Ronald Bultje <rbultje@ronald.bitfreak.net>");
118 }
119
120
121 /**
122  * gst_amr_parse_class_init:
123  * @klass: GstAmrParseClass.
124  *
125  */
126 static void
127 gst_amr_parse_class_init (GstAmrParseClass * klass)
128 {
129   GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass);
130
131   parse_class->start = GST_DEBUG_FUNCPTR (gst_amr_parse_start);
132   parse_class->stop = GST_DEBUG_FUNCPTR (gst_amr_parse_stop);
133   parse_class->set_sink_caps = GST_DEBUG_FUNCPTR (gst_amr_parse_sink_setcaps);
134   parse_class->get_sink_caps = GST_DEBUG_FUNCPTR (gst_amr_parse_sink_getcaps);
135   parse_class->parse_frame = GST_DEBUG_FUNCPTR (gst_amr_parse_parse_frame);
136   parse_class->check_valid_frame =
137       GST_DEBUG_FUNCPTR (gst_amr_parse_check_valid_frame);
138
139 #ifdef GST_EXT_AMRPARSER_MODIFICATION /* make full amr index table when seek */
140   parse_class->src_event = gst_amr_parse_src_eventfunc;
141 #endif
142 }
143
144
145 /**
146  * gst_amr_parse_init:
147  * @amrparse: #GstAmrParse
148  * @klass: #GstAmrParseClass.
149  *
150  */
151 static void
152 gst_amr_parse_init (GstAmrParse * amrparse, GstAmrParseClass * klass)
153 {
154   /* init rest */
155   gst_base_parse_set_min_frame_size (GST_BASE_PARSE (amrparse), 62);
156   GST_DEBUG ("initialized");
157
158 }
159
160
161 /**
162  * gst_amr_parse_set_src_caps:
163  * @amrparse: #GstAmrParse.
164  *
165  * Set source pad caps according to current knowledge about the
166  * audio stream.
167  *
168  * Returns: TRUE if caps were successfully set.
169  */
170 static gboolean
171 gst_amr_parse_set_src_caps (GstAmrParse * amrparse)
172 {
173   GstCaps *src_caps = NULL;
174   gboolean res = FALSE;
175
176   if (amrparse->wide) {
177     GST_DEBUG_OBJECT (amrparse, "setting srcpad caps to AMR-WB");
178     src_caps = gst_caps_new_simple ("audio/AMR-WB",
179         "channels", G_TYPE_INT, 1, "rate", G_TYPE_INT, 16000, NULL);
180   } else {
181     GST_DEBUG_OBJECT (amrparse, "setting srcpad caps to AMR-NB");
182     /* Max. size of NB frame is 31 bytes, so we can set the min. frame
183        size to 32 (+1 for next frame header) */
184     gst_base_parse_set_min_frame_size (GST_BASE_PARSE (amrparse), 32);
185     src_caps = gst_caps_new_simple ("audio/AMR",
186         "channels", G_TYPE_INT, 1, "rate", G_TYPE_INT, 8000, NULL);
187   }
188   gst_pad_use_fixed_caps (GST_BASE_PARSE (amrparse)->srcpad);
189   res = gst_pad_set_caps (GST_BASE_PARSE (amrparse)->srcpad, src_caps);
190   gst_caps_unref (src_caps);
191   return res;
192 }
193
194
195 /**
196  * gst_amr_parse_sink_setcaps:
197  * @sinkpad: GstPad
198  * @caps: GstCaps
199  *
200  * Returns: TRUE on success.
201  */
202 static gboolean
203 gst_amr_parse_sink_setcaps (GstBaseParse * parse, GstCaps * caps)
204 {
205   GstAmrParse *amrparse;
206   GstStructure *structure;
207   const gchar *name;
208
209   amrparse = GST_AMR_PARSE (parse);
210   structure = gst_caps_get_structure (caps, 0);
211   name = gst_structure_get_name (structure);
212
213   GST_DEBUG_OBJECT (amrparse, "setcaps: %s", name);
214
215   if (!strncmp (name, "audio/x-amr-wb-sh", 17)) {
216     amrparse->block_size = block_size_wb;
217     amrparse->wide = 1;
218   } else if (!strncmp (name, "audio/x-amr-nb-sh", 17)) {
219     amrparse->block_size = block_size_nb;
220     amrparse->wide = 0;
221   } else {
222     GST_WARNING ("Unknown caps");
223     return FALSE;
224   }
225
226   amrparse->need_header = FALSE;
227   gst_base_parse_set_frame_rate (GST_BASE_PARSE (amrparse), 50, 1, 2, 2);
228   gst_amr_parse_set_src_caps (amrparse);
229   return TRUE;
230 }
231
232 /**
233  * gst_amr_parse_parse_header:
234  * @amrparse: #GstAmrParse
235  * @data: Header data to be parsed.
236  * @skipsize: Output argument where the frame size will be stored.
237  *
238  * Check if the given data contains an AMR mime header.
239  *
240  * Returns: TRUE on success.
241  */
242 static gboolean
243 gst_amr_parse_parse_header (GstAmrParse * amrparse,
244     const guint8 * data, gint * skipsize)
245 {
246   GST_DEBUG_OBJECT (amrparse, "Parsing header data");
247
248   if (!memcmp (data, "#!AMR-WB\n", 9)) {
249     GST_DEBUG_OBJECT (amrparse, "AMR-WB detected");
250     amrparse->block_size = block_size_wb;
251     amrparse->wide = TRUE;
252     *skipsize = amrparse->header = 9;
253   } else if (!memcmp (data, "#!AMR\n", 6)) {
254     GST_DEBUG_OBJECT (amrparse, "AMR-NB detected");
255     amrparse->block_size = block_size_nb;
256     amrparse->wide = FALSE;
257     *skipsize = amrparse->header = 6;
258   } else
259     return FALSE;
260
261   gst_amr_parse_set_src_caps (amrparse);
262   return TRUE;
263 }
264
265
266 /**
267  * gst_amr_parse_check_valid_frame:
268  * @parse: #GstBaseParse.
269  * @buffer: #GstBuffer.
270  * @framesize: Output variable where the found frame size is put.
271  * @skipsize: Output variable which tells how much data needs to be skipped
272  *            until a frame header is found.
273  *
274  * Implementation of "check_valid_frame" vmethod in #GstBaseParse class.
275  *
276  * Returns: TRUE if the given data contains valid frame.
277  */
278 static gboolean
279 gst_amr_parse_check_valid_frame (GstBaseParse * parse,
280     GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
281 {
282   GstBuffer *buffer;
283   const guint8 *data;
284   gint fsize, mode, dsize;
285   GstAmrParse *amrparse;
286
287   amrparse = GST_AMR_PARSE (parse);
288   buffer = frame->buffer;
289   data = GST_BUFFER_DATA (buffer);
290   dsize = GST_BUFFER_SIZE (buffer);
291
292   GST_LOG ("buffer: %d bytes", dsize);
293
294   if (amrparse->need_header) {
295     if (dsize >= AMR_MIME_HEADER_SIZE &&
296         gst_amr_parse_parse_header (amrparse, data, skipsize)) {
297       amrparse->need_header = FALSE;
298       gst_base_parse_set_frame_rate (GST_BASE_PARSE (amrparse), 50, 1, 2, 2);
299     } else {
300       GST_WARNING ("media doesn't look like a AMR format");
301     }
302     /* We return FALSE, so this frame won't get pushed forward. Instead,
303        the "skip" value is set, so next time we will receive a valid frame. */
304     return FALSE;
305   }
306
307   /* Does this look like a possible frame header candidate? */
308   if ((data[0] & 0x83) == 0) {
309     /* Yep. Retrieve the frame size */
310     mode = (data[0] >> 3) & 0x0F;
311     fsize = amrparse->block_size[mode] + 1;     /* +1 for the header byte */
312
313     /* We recognize this data as a valid frame when:
314      *     - We are in sync. There is no need for extra checks then
315      *     - We are in EOS. There might not be enough data to check next frame
316      *     - Sync is lost, but the following data after this frame seem
317      *       to contain a valid header as well (and there is enough data to
318      *       perform this check)
319      */
320     if (fsize) {
321       gboolean found = FALSE;
322
323       /* in sync, no further check */
324       if (!GST_BASE_PARSE_LOST_SYNC (parse)) {
325         found = TRUE;
326       } else if (dsize > fsize) {
327         /* enough data, check for next sync */
328         if ((data[fsize] & 0x83) == 0)
329           found = TRUE;
330       } else if (GST_BASE_PARSE_DRAINING (parse)) {
331         /* not enough, but draining, so ok */
332         found = TRUE;
333       } else {
334         /* indicate we need not skip, but need more data */
335         *skipsize = 0;
336         *framesize = fsize + 1;
337       }
338       if (found) {
339         *framesize = fsize;
340         return TRUE;
341       }
342     }
343   }
344
345   GST_LOG ("sync lost");
346   return FALSE;
347 }
348
349
350 /**
351  * gst_amr_parse_parse_frame:
352  * @parse: #GstBaseParse.
353  * @buffer: #GstBuffer.
354  *
355  * Implementation of "parse" vmethod in #GstBaseParse class.
356  *
357  * Returns: #GstFlowReturn defining the parsing status.
358  */
359 static GstFlowReturn
360 gst_amr_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
361 {
362   return GST_FLOW_OK;
363 }
364
365
366 /**
367  * gst_amr_parse_start:
368  * @parse: #GstBaseParse.
369  *
370  * Implementation of "start" vmethod in #GstBaseParse class.
371  *
372  * Returns: TRUE on success.
373  */
374 static gboolean
375 gst_amr_parse_start (GstBaseParse * parse)
376 {
377   GstAmrParse *amrparse;
378
379   amrparse = GST_AMR_PARSE (parse);
380   GST_DEBUG ("start");
381   amrparse->need_header = TRUE;
382   amrparse->header = 0;
383   return TRUE;
384 }
385
386
387 /**
388  * gst_amr_parse_stop:
389  * @parse: #GstBaseParse.
390  *
391  * Implementation of "stop" vmethod in #GstBaseParse class.
392  *
393  * Returns: TRUE on success.
394  */
395 static gboolean
396 gst_amr_parse_stop (GstBaseParse * parse)
397 {
398   GstAmrParse *amrparse;
399
400   amrparse = GST_AMR_PARSE (parse);
401   GST_DEBUG ("stop");
402   amrparse->need_header = TRUE;
403   amrparse->header = 0;
404   return TRUE;
405 }
406
407 static GstCaps *
408 gst_amr_parse_sink_getcaps (GstBaseParse * parse)
409 {
410   GstCaps *peercaps;
411   GstCaps *res;
412
413   peercaps = gst_pad_get_allowed_caps (GST_BASE_PARSE_SRC_PAD (parse));
414   if (peercaps) {
415     guint i, n;
416
417     /* Rename structure names */
418     peercaps = gst_caps_make_writable (peercaps);
419     n = gst_caps_get_size (peercaps);
420     for (i = 0; i < n; i++) {
421       GstStructure *s = gst_caps_get_structure (peercaps, i);
422
423       if (gst_structure_has_name (s, "audio/AMR"))
424         gst_structure_set_name (s, "audio/x-amr-nb-sh");
425       else
426         gst_structure_set_name (s, "audio/x-amr-wb-sh");
427     }
428
429     res =
430         gst_caps_intersect_full (peercaps,
431         gst_pad_get_pad_template_caps (GST_BASE_PARSE_SRC_PAD (parse)),
432         GST_CAPS_INTERSECT_FIRST);
433     gst_caps_unref (peercaps);
434   } else {
435     res =
436         gst_caps_copy (gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD
437             (parse)));
438   }
439
440   return res;
441 }
442
443
444 #ifdef GST_EXT_AMRPARSER_MODIFICATION /* make full amr index table when seek */
445 /**
446  * gst_amr_parse_src_eventfunc:
447  * @parse: #GstBaseParse. #event
448  *
449  * before baseparse handles seek event, make full amr index table.
450  *
451  * Returns: TRUE on success.
452  */
453 static gboolean
454 gst_amr_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
455 {
456   gboolean handled = FALSE;
457   GstAmrParse *amrparse;
458   amrparse = GST_AMR_PARSE (parse);
459
460   switch (GST_EVENT_TYPE (event)) {
461     case GST_EVENT_SEEK:
462       {
463         GstFlowReturn res = GST_FLOW_OK;
464         gint64 base_offset = 0, sync_offset = 0, cur = 0;
465         gint32 frame_count = 1; /* do not add first frame because it is already in index table */
466         gint64 total_file_size = 0, start_offset = 0;
467         GstClockTime current_ts = GST_CLOCK_TIME_NONE;
468         GstActivateMode pad_mode = GST_ACTIVATE_NONE;
469
470 #ifdef GST_EXT_BASEPARSER_MODIFICATION /* check baseparse define these fuction */
471         gst_base_parse_get_pad_mode(parse, &pad_mode);
472         if (pad_mode != GST_ACTIVATE_PULL) {
473           GST_INFO_OBJECT (amrparse, "arm parser is not pull mode. amr parser can not make index table.");
474           return FALSE;
475         }
476         gst_base_parse_get_upstream_size(parse, &total_file_size);
477         gst_base_parse_get_index_last_offset(parse, &start_offset);
478         gst_base_parse_get_index_last_ts(parse, &current_ts);
479 #else
480         GST_WARNING_OBJECT (amrparse, "baseparser does not define get private param functions. can not make index table here.");
481         break;
482 #endif
483
484         GST_LOG_OBJECT (amrparse, "gst_amr_parse_src_eventfunc GST_EVENT_SEEK enter");
485
486         if (total_file_size == 0 || start_offset >= total_file_size) {
487           GST_ERROR("last index offset %d is larger than file size %d", start_offset, total_file_size);
488           break;
489         }
490
491         gst_event_parse_seek (event, NULL, NULL, NULL, NULL, &cur, NULL, NULL);
492         if (cur <= current_ts) {
493           GST_INFO_OBJECT (amrparse, "seek to %"GST_TIME_FORMAT" within index table %"GST_TIME_FORMAT". do not make index table",
494               GST_TIME_ARGS(cur), GST_TIME_ARGS(current_ts));
495           break;
496         } else {
497           GST_INFO_OBJECT (amrparse, "seek to %"GST_TIME_FORMAT" without index table %"GST_TIME_FORMAT". make index table",
498               GST_TIME_ARGS(cur), GST_TIME_ARGS(current_ts));
499         }
500
501         GST_INFO_OBJECT (amrparse, "make AMR Index Table. file_size  = %"G_GINT64_FORMAT" last idx offset=%"G_GINT64_FORMAT
502             ", last idx ts=%"GST_TIME_FORMAT, total_file_size, start_offset, GST_TIME_ARGS(current_ts));
503
504         base_offset = start_offset; /* set base by start offset */
505
506
507         /* STEP 1: MAX_PULL_RANGE_BUF cycle */
508         while (total_file_size - base_offset >= AMR_MAX_PULL_RANGE_BUF) {
509           gint64 offset = 0;
510           GstBuffer *buffer = NULL;
511           guint8 *buf = NULL;
512
513          GST_INFO_OBJECT (amrparse, "gst_pad_pull_range %d bytes (from %"G_GINT64_FORMAT") use max size", AMR_MAX_PULL_RANGE_BUF, base_offset);
514           res = gst_pad_pull_range (parse->sinkpad, base_offset,
515               base_offset + AMR_MAX_PULL_RANGE_BUF, &buffer);
516           if (res != GST_FLOW_OK) {
517             GST_ERROR_OBJECT (amrparse, "gst_pad_pull_range failed!");
518             break;
519           }
520
521           buf = GST_BUFFER_DATA(buffer);
522
523           while (offset <= AMR_MAX_PULL_RANGE_BUF) {
524             gint mode = 0,  frame_size = 0;
525
526             if (buf != NULL && ((buf[offset] & 0x83) == 0)) {
527               mode = (buf[offset] >> 3) & 0x0F;
528               frame_size = amrparse->block_size[mode] + 1; /* +1 for the header byte */
529
530               if (frame_count % 50 == 0) { /* 1 sec == 50 frames. we make idx per sec */
531 //                gst_base_parse_add_index_entry (parse, base_offset +offset - (amrparse->wide ? 9 : 6), current_ts, TRUE, TRUE); /* force */
532                 gst_base_parse_add_index_entry (parse, base_offset +offset, current_ts, TRUE, TRUE); /* force */
533                 GST_DEBUG_OBJECT (amrparse, "Adding  index ts=%"GST_TIME_FORMAT" offset %"G_GINT64_FORMAT,
534                     GST_TIME_ARGS(current_ts), base_offset + offset);
535               }
536
537               current_ts += 20 * 1000 * 1000; /* each frame is 20ms */
538               offset += frame_size;
539               frame_count++;
540             } else {
541               GST_WARNING_OBJECT (amrparse, "we lost sync");
542               offset++;
543             }
544           } /* while */
545         base_offset = base_offset + offset;
546         gst_buffer_unref (buffer);
547         } /* end MAX buffer cycle */
548
549
550         /* STEP 2: Remain Buffer cycle */
551         if (total_file_size - base_offset > 0) {
552           gint64 offset = 0;
553           GstBuffer *buffer = NULL;
554           guint8 *buf = NULL;
555
556           GST_INFO_OBJECT (amrparse, "gst_pad_pull_range %"G_GINT64_FORMAT" bytes (from %"G_GINT64_FORMAT") use remain_buf size",
557               total_file_size - base_offset, base_offset);
558           res = gst_pad_pull_range (parse->sinkpad, base_offset,
559               total_file_size, &buffer);
560           if (res != GST_FLOW_OK) {
561             GST_ERROR ("gst_pad_pull_range failed!");
562             break;
563           }
564
565           buf = GST_BUFFER_DATA(buffer);
566
567           while (base_offset + offset < total_file_size) {
568             gint mode = 0, frame_size = 0;
569
570             if (buf != NULL && ((buf[offset] & 0x83) == 0)) {
571               mode = (buf[offset] >> 3) & 0x0F;
572               frame_size = amrparse->block_size[mode] + 1; /* +1 for the header byte */
573
574               if (frame_count % 50 == 0) { /* 1 sec == 50 frames. we make idx per sec */
575                 gst_base_parse_add_index_entry (parse, base_offset +offset, current_ts, TRUE, TRUE); /* force */
576                 GST_DEBUG_OBJECT (amrparse, "Adding  index ts=%"GST_TIME_FORMAT" offset %"G_GINT64_FORMAT,
577                     GST_TIME_ARGS(current_ts), base_offset + offset);
578               }
579
580               current_ts += 20 * 1000 * 1000; /* each frame is 20ms */
581               offset += frame_size;
582               frame_count++;
583             } else {
584               GST_WARNING_OBJECT (amrparse, "we lost sync");
585               offset++;
586             }
587           } /* while */
588
589         gst_buffer_unref (buffer);
590         } /* end remain_buf buffer cycle */
591
592         GST_LOG_OBJECT (amrparse, "gst_amr_parse_src_eventfunc GST_EVENT_SEEK leave");
593       }
594      break;
595
596     default:
597       break;
598   }
599
600   /* call baseparse src_event function to handle event */
601   handled = GST_BASE_PARSE_CLASS (parent_class)->src_event (parse, event);
602
603   return handled;
604 }
605 #endif