RTPencode.cc revision b7e5054414ff524f9db81dab7917729b8c4c8bcb
1/*
2 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 *  Use of this source code is governed by a BSD-style license
5 *  that can be found in the LICENSE file in the root of the source
6 *  tree. An additional intellectual property rights grant can be found
7 *  in the file PATENTS.  All contributing project authors may
8 *  be found in the AUTHORS file in the root of the source tree.
9 */
10
11// TODO(hlundin): Reformat file to meet style guide.
12
13/* header includes */
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#ifdef WIN32
18#include <winsock2.h>
19#endif
20#ifdef WEBRTC_LINUX
21#include <netinet/in.h>
22#endif
23
24#include <assert.h>
25
26#include "webrtc/typedefs.h"
27// needed for NetEqDecoder
28#include "webrtc/modules/audio_coding/neteq/audio_decoder_impl.h"
29#include "webrtc/modules/audio_coding/neteq/interface/neteq.h"
30
31/************************/
32/* Define payload types */
33/************************/
34
35#include "PayloadTypes.h"
36
37/*********************/
38/* Misc. definitions */
39/*********************/
40
41#define STOPSENDTIME 3000
42#define RESTARTSENDTIME 0  // 162500
43#define FIRSTLINELEN 40
44#define CHECK_NOT_NULL(a)                                                \
45  if ((a) == 0) {                                                        \
46    printf("\n %s \n line: %d \nerror at %s\n", __FILE__, __LINE__, #a); \
47    return (-1);                                                         \
48  }
49
50//#define MULTIPLE_SAME_TIMESTAMP
51#define REPEAT_PACKET_DISTANCE 17
52#define REPEAT_PACKET_COUNT 1  // number of extra packets to send
53
54//#define INSERT_OLD_PACKETS
55#define OLD_PACKET 5  // how many seconds too old should the packet be?
56
57//#define TIMESTAMP_WRAPAROUND
58
59//#define RANDOM_DATA
60//#define RANDOM_PAYLOAD_DATA
61#define RANDOM_SEED 10
62
63//#define INSERT_DTMF_PACKETS
64//#define NO_DTMF_OVERDUB
65#define DTMF_PACKET_INTERVAL 2000
66#define DTMF_DURATION 500
67
68#define STEREO_MODE_FRAME 0
69#define STEREO_MODE_SAMPLE_1 1  // 1 octet per sample
70#define STEREO_MODE_SAMPLE_2 2  // 2 octets per sample
71
72/*************************/
73/* Function declarations */
74/*************************/
75
76void NetEQTest_GetCodec_and_PT(char* name,
77                               webrtc::NetEqDecoder* codec,
78                               int* PT,
79                               int frameLen,
80                               int* fs,
81                               int* bitrate,
82                               int* useRed);
83int NetEQTest_init_coders(webrtc::NetEqDecoder coder,
84                          int enc_frameSize,
85                          int bitrate,
86                          int sampfreq,
87                          int vad,
88                          int numChannels);
89void defineCodecs(webrtc::NetEqDecoder* usedCodec, int* noOfCodecs);
90int NetEQTest_free_coders(webrtc::NetEqDecoder coder, int numChannels);
91int NetEQTest_encode(int coder,
92                     int16_t* indata,
93                     int frameLen,
94                     unsigned char* encoded,
95                     int sampleRate,
96                     int* vad,
97                     int useVAD,
98                     int bitrate,
99                     int numChannels);
100void makeRTPheader(unsigned char* rtp_data,
101                   int payloadType,
102                   int seqNo,
103                   uint32_t timestamp,
104                   uint32_t ssrc);
105int makeRedundantHeader(unsigned char* rtp_data,
106                        int* payloadType,
107                        int numPayloads,
108                        uint32_t* timestamp,
109                        uint16_t* blockLen,
110                        int seqNo,
111                        uint32_t ssrc);
112int makeDTMFpayload(unsigned char* payload_data,
113                    int Event,
114                    int End,
115                    int Volume,
116                    int Duration);
117void stereoDeInterleave(int16_t* audioSamples, int numSamples);
118void stereoInterleave(unsigned char* data, int dataLen, int stride);
119
120/*********************/
121/* Codec definitions */
122/*********************/
123
124#include "webrtc_vad.h"
125
126#if ((defined CODEC_PCM16B) || (defined NETEQ_ARBITRARY_CODEC))
127#include "pcm16b.h"
128#endif
129#ifdef CODEC_G711
130#include "g711_interface.h"
131#endif
132#ifdef CODEC_G729
133#include "G729Interface.h"
134#endif
135#ifdef CODEC_G729_1
136#include "G729_1Interface.h"
137#endif
138#ifdef CODEC_AMR
139#include "AMRInterface.h"
140#include "AMRCreation.h"
141#endif
142#ifdef CODEC_AMRWB
143#include "AMRWBInterface.h"
144#include "AMRWBCreation.h"
145#endif
146#ifdef CODEC_ILBC
147#include "ilbc.h"
148#endif
149#if (defined CODEC_ISAC || defined CODEC_ISAC_SWB)
150#include "isac.h"
151#endif
152#ifdef NETEQ_ISACFIX_CODEC
153#include "isacfix.h"
154#ifdef CODEC_ISAC
155#error Cannot have both ISAC and ISACfix defined. Please de-select one in the beginning of RTPencode.cpp
156#endif
157#endif
158#ifdef CODEC_G722
159#include "g722_interface.h"
160#endif
161#ifdef CODEC_G722_1_24
162#include "G722_1Interface.h"
163#endif
164#ifdef CODEC_G722_1_32
165#include "G722_1Interface.h"
166#endif
167#ifdef CODEC_G722_1_16
168#include "G722_1Interface.h"
169#endif
170#ifdef CODEC_G722_1C_24
171#include "G722_1Interface.h"
172#endif
173#ifdef CODEC_G722_1C_32
174#include "G722_1Interface.h"
175#endif
176#ifdef CODEC_G722_1C_48
177#include "G722_1Interface.h"
178#endif
179#ifdef CODEC_G726
180#include "G726Creation.h"
181#include "G726Interface.h"
182#endif
183#ifdef CODEC_GSMFR
184#include "GSMFRInterface.h"
185#include "GSMFRCreation.h"
186#endif
187#if (defined(CODEC_CNGCODEC8) || defined(CODEC_CNGCODEC16) || \
188     defined(CODEC_CNGCODEC32) || defined(CODEC_CNGCODEC48))
189#include "webrtc_cng.h"
190#endif
191#if ((defined CODEC_SPEEX_8) || (defined CODEC_SPEEX_16))
192#include "SpeexInterface.h"
193#endif
194
195/***********************************/
196/* Global codec instance variables */
197/***********************************/
198
199WebRtcVadInst* VAD_inst[2];
200
201#ifdef CODEC_G722
202G722EncInst* g722EncState[2];
203#endif
204
205#ifdef CODEC_G722_1_24
206G722_1_24_encinst_t* G722_1_24enc_inst[2];
207#endif
208#ifdef CODEC_G722_1_32
209G722_1_32_encinst_t* G722_1_32enc_inst[2];
210#endif
211#ifdef CODEC_G722_1_16
212G722_1_16_encinst_t* G722_1_16enc_inst[2];
213#endif
214#ifdef CODEC_G722_1C_24
215G722_1C_24_encinst_t* G722_1C_24enc_inst[2];
216#endif
217#ifdef CODEC_G722_1C_32
218G722_1C_32_encinst_t* G722_1C_32enc_inst[2];
219#endif
220#ifdef CODEC_G722_1C_48
221G722_1C_48_encinst_t* G722_1C_48enc_inst[2];
222#endif
223#ifdef CODEC_G726
224G726_encinst_t* G726enc_inst[2];
225#endif
226#ifdef CODEC_G729
227G729_encinst_t* G729enc_inst[2];
228#endif
229#ifdef CODEC_G729_1
230G729_1_inst_t* G729_1_inst[2];
231#endif
232#ifdef CODEC_AMR
233AMR_encinst_t* AMRenc_inst[2];
234int16_t AMR_bitrate;
235#endif
236#ifdef CODEC_AMRWB
237AMRWB_encinst_t* AMRWBenc_inst[2];
238int16_t AMRWB_bitrate;
239#endif
240#ifdef CODEC_ILBC
241IlbcEncoderInstance* iLBCenc_inst[2];
242#endif
243#ifdef CODEC_ISAC
244ISACStruct* ISAC_inst[2];
245#endif
246#ifdef NETEQ_ISACFIX_CODEC
247ISACFIX_MainStruct* ISAC_inst[2];
248#endif
249#ifdef CODEC_ISAC_SWB
250ISACStruct* ISACSWB_inst[2];
251#endif
252#ifdef CODEC_GSMFR
253GSMFR_encinst_t* GSMFRenc_inst[2];
254#endif
255#if (defined(CODEC_CNGCODEC8) || defined(CODEC_CNGCODEC16) || \
256     defined(CODEC_CNGCODEC32) || defined(CODEC_CNGCODEC48))
257CNG_enc_inst* CNGenc_inst[2];
258#endif
259#ifdef CODEC_SPEEX_8
260SPEEX_encinst_t* SPEEX8enc_inst[2];
261#endif
262#ifdef CODEC_SPEEX_16
263SPEEX_encinst_t* SPEEX16enc_inst[2];
264#endif
265
266int main(int argc, char* argv[]) {
267  int packet_size, fs;
268  webrtc::NetEqDecoder usedCodec;
269  int payloadType;
270  int bitrate = 0;
271  int useVAD, vad;
272  int useRed = 0;
273  int len, enc_len;
274  int16_t org_data[4000];
275  unsigned char rtp_data[8000];
276  int16_t seqNo = 0xFFF;
277  uint32_t ssrc = 1235412312;
278  uint32_t timestamp = 0xAC1245;
279  uint16_t length, plen;
280  uint32_t offset;
281  double sendtime = 0;
282  int red_PT[2] = {0};
283  uint32_t red_TS[2] = {0};
284  uint16_t red_len[2] = {0};
285  int RTPheaderLen = 12;
286  uint8_t red_data[8000];
287#ifdef INSERT_OLD_PACKETS
288  uint16_t old_length, old_plen;
289  int old_enc_len;
290  int first_old_packet = 1;
291  unsigned char old_rtp_data[8000];
292  int packet_age = 0;
293#endif
294#ifdef INSERT_DTMF_PACKETS
295  int NTone = 1;
296  int DTMFfirst = 1;
297  uint32_t DTMFtimestamp;
298  bool dtmfSent = false;
299#endif
300  bool usingStereo = false;
301  int stereoMode = 0;
302  int numChannels = 1;
303
304  /* check number of parameters */
305  if ((argc != 6) && (argc != 7)) {
306    /* print help text and exit */
307    printf("Application to encode speech into an RTP stream.\n");
308    printf("The program reads a PCM file and encodes is using the specified "
309           "codec.\n");
310    printf("The coded speech is packetized in RTP packest and written to the "
311           "output file.\n");
312    printf("The format of the RTP stream file is simlilar to that of "
313           "rtpplay,\n");
314    printf("but with the receive time euqal to 0 for all packets.\n");
315    printf("Usage:\n\n");
316    printf("%s PCMfile RTPfile frameLen codec useVAD bitrate\n", argv[0]);
317    printf("where:\n");
318
319    printf("PCMfile      : PCM speech input file\n\n");
320
321    printf("RTPfile      : RTP stream output file\n\n");
322
323    printf("frameLen     : 80...960...  Number of samples per packet (limit "
324           "depends on codec)\n\n");
325
326    printf("codecName\n");
327#ifdef CODEC_PCM16B
328    printf("             : pcm16b       16 bit PCM (8kHz)\n");
329#endif
330#ifdef CODEC_PCM16B_WB
331    printf("             : pcm16b_wb   16 bit PCM (16kHz)\n");
332#endif
333#ifdef CODEC_PCM16B_32KHZ
334    printf("             : pcm16b_swb32 16 bit PCM (32kHz)\n");
335#endif
336#ifdef CODEC_PCM16B_48KHZ
337    printf("             : pcm16b_swb48 16 bit PCM (48kHz)\n");
338#endif
339#ifdef CODEC_G711
340    printf("             : pcma         g711 A-law (8kHz)\n");
341#endif
342#ifdef CODEC_G711
343    printf("             : pcmu         g711 u-law (8kHz)\n");
344#endif
345#ifdef CODEC_G729
346    printf("             : g729         G729 (8kHz and 8kbps) CELP (One-Three "
347           "frame(s)/packet)\n");
348#endif
349#ifdef CODEC_G729_1
350    printf("             : g729.1       G729.1 (16kHz) variable rate (8--32 "
351           "kbps)\n");
352#endif
353#ifdef CODEC_G722_1_16
354    printf("             : g722.1_16    G722.1 coder (16kHz) (g722.1 with "
355           "16kbps)\n");
356#endif
357#ifdef CODEC_G722_1_24
358    printf("             : g722.1_24    G722.1 coder (16kHz) (the 24kbps "
359           "version)\n");
360#endif
361#ifdef CODEC_G722_1_32
362    printf("             : g722.1_32    G722.1 coder (16kHz) (the 32kbps "
363           "version)\n");
364#endif
365#ifdef CODEC_G722_1C_24
366    printf("             : g722.1C_24    G722.1 C coder (32kHz) (the 24kbps "
367           "version)\n");
368#endif
369#ifdef CODEC_G722_1C_32
370    printf("             : g722.1C_32    G722.1 C coder (32kHz) (the 32kbps "
371           "version)\n");
372#endif
373#ifdef CODEC_G722_1C_48
374    printf("             : g722.1C_48    G722.1 C coder (32kHz) (the 48kbps "
375           "version)\n");
376#endif
377
378#ifdef CODEC_G726
379    printf("             : g726_16      G726 coder (8kHz) 16kbps\n");
380    printf("             : g726_24      G726 coder (8kHz) 24kbps\n");
381    printf("             : g726_32      G726 coder (8kHz) 32kbps\n");
382    printf("             : g726_40      G726 coder (8kHz) 40kbps\n");
383#endif
384#ifdef CODEC_AMR
385    printf("             : AMRXk        Adaptive Multi Rate CELP codec "
386           "(8kHz)\n");
387    printf("                            X = 4.75, 5.15, 5.9, 6.7, 7.4, 7.95, "
388           "10.2 or 12.2\n");
389#endif
390#ifdef CODEC_AMRWB
391    printf("             : AMRwbXk      Adaptive Multi Rate Wideband CELP "
392           "codec (16kHz)\n");
393    printf("                            X = 7, 9, 12, 14, 16, 18, 20, 23 or "
394           "24\n");
395#endif
396#ifdef CODEC_ILBC
397    printf("             : ilbc         iLBC codec (8kHz and 13.8kbps)\n");
398#endif
399#ifdef CODEC_ISAC
400    printf("             : isac         iSAC (16kHz and 32.0 kbps). To set "
401           "rate specify a rate parameter as last parameter\n");
402#endif
403#ifdef CODEC_ISAC_SWB
404    printf("             : isacswb       iSAC SWB (32kHz and 32.0-52.0 kbps). "
405           "To set rate specify a rate parameter as last parameter\n");
406#endif
407#ifdef CODEC_GSMFR
408    printf("             : gsmfr        GSM FR codec (8kHz and 13kbps)\n");
409#endif
410#ifdef CODEC_G722
411    printf("             : g722         g722 coder (16kHz) (the 64kbps "
412           "version)\n");
413#endif
414#ifdef CODEC_SPEEX_8
415    printf("             : speex8       speex coder (8 kHz)\n");
416#endif
417#ifdef CODEC_SPEEX_16
418    printf("             : speex16      speex coder (16 kHz)\n");
419#endif
420#ifdef CODEC_RED
421#ifdef CODEC_G711
422    printf("             : red_pcm      Redundancy RTP packet with 2*G711A "
423           "frames\n");
424#endif
425#ifdef CODEC_ISAC
426    printf("             : red_isac     Redundancy RTP packet with 2*iSAC "
427           "frames\n");
428#endif
429#endif
430    printf("\n");
431
432#if (defined(CODEC_CNGCODEC8) || defined(CODEC_CNGCODEC16) || \
433     defined(CODEC_CNGCODEC32) || defined(CODEC_CNGCODEC48))
434    printf("useVAD       : 0 Voice Activity Detection is switched off\n");
435    printf("             : 1 Voice Activity Detection is switched on\n\n");
436#else
437    printf("useVAD       : 0 Voice Activity Detection switched off (on not "
438           "supported)\n\n");
439#endif
440    printf("bitrate      : Codec bitrate in bps (only applies to vbr "
441           "codecs)\n\n");
442
443    return (0);
444  }
445
446  FILE* in_file = fopen(argv[1], "rb");
447  CHECK_NOT_NULL(in_file);
448  printf("Input file: %s\n", argv[1]);
449  FILE* out_file = fopen(argv[2], "wb");
450  CHECK_NOT_NULL(out_file);
451  printf("Output file: %s\n\n", argv[2]);
452  packet_size = atoi(argv[3]);
453  if (packet_size <= 0) {
454     printf("Packet size %d must be positive", packet_size);
455     return -1;
456  }
457  printf("Packet size: %i\n", packet_size);
458
459  // check for stereo
460  if (argv[4][strlen(argv[4]) - 1] == '*') {
461    // use stereo
462    usingStereo = true;
463    numChannels = 2;
464    argv[4][strlen(argv[4]) - 1] = '\0';
465  }
466
467  NetEQTest_GetCodec_and_PT(argv[4], &usedCodec, &payloadType, packet_size, &fs,
468                            &bitrate, &useRed);
469
470  if (useRed) {
471    RTPheaderLen = 12 + 4 + 1; /* standard RTP = 12; 4 bytes per redundant
472                                  payload, except last one which is 1 byte */
473  }
474
475  useVAD = atoi(argv[5]);
476#if !(defined(CODEC_CNGCODEC8) || defined(CODEC_CNGCODEC16) || \
477      defined(CODEC_CNGCODEC32) || defined(CODEC_CNGCODEC48))
478  if (useVAD != 0) {
479    printf("Error: this simulation does not support VAD/DTX/CNG\n");
480  }
481#endif
482
483  // check stereo type
484  if (usingStereo) {
485    switch (usedCodec) {
486      // sample based codecs
487      case webrtc::kDecoderPCMu:
488      case webrtc::kDecoderPCMa:
489      case webrtc::kDecoderG722: {
490        // 1 octet per sample
491        stereoMode = STEREO_MODE_SAMPLE_1;
492        break;
493      }
494      case webrtc::kDecoderPCM16B:
495      case webrtc::kDecoderPCM16Bwb:
496      case webrtc::kDecoderPCM16Bswb32kHz:
497      case webrtc::kDecoderPCM16Bswb48kHz: {
498        // 2 octets per sample
499        stereoMode = STEREO_MODE_SAMPLE_2;
500        break;
501      }
502
503      // fixed-rate frame codecs (with internal VAD)
504      default: {
505        printf("Cannot use codec %s as stereo codec\n", argv[4]);
506        exit(0);
507      }
508    }
509  }
510
511  if ((usedCodec == webrtc::kDecoderISAC) ||
512      (usedCodec == webrtc::kDecoderISACswb)) {
513    if (argc != 7) {
514      if (usedCodec == webrtc::kDecoderISAC) {
515        bitrate = 32000;
516        printf("Running iSAC at default bitrate of 32000 bps (to specify "
517               "explicitly add the bps as last parameter)\n");
518      } else  // (usedCodec==webrtc::kDecoderISACswb)
519      {
520        bitrate = 56000;
521        printf("Running iSAC at default bitrate of 56000 bps (to specify "
522               "explicitly add the bps as last parameter)\n");
523      }
524    } else {
525      bitrate = atoi(argv[6]);
526      if (usedCodec == webrtc::kDecoderISAC) {
527        if ((bitrate < 10000) || (bitrate > 32000)) {
528          printf("Error: iSAC bitrate must be between 10000 and 32000 bps (%i "
529                 "is invalid)\n", bitrate);
530          exit(0);
531        }
532        printf("Running iSAC at bitrate of %i bps\n", bitrate);
533      } else  // (usedCodec==webrtc::kDecoderISACswb)
534      {
535        if ((bitrate < 32000) || (bitrate > 56000)) {
536          printf("Error: iSAC SWB bitrate must be between 32000 and 56000 bps "
537                 "(%i is invalid)\n", bitrate);
538          exit(0);
539        }
540      }
541    }
542  } else {
543    if (argc == 7) {
544      printf("Error: Bitrate parameter can only be specified for iSAC, G.723, "
545             "and G.729.1\n");
546      exit(0);
547    }
548  }
549
550  if (useRed) {
551    printf("Redundancy engaged. ");
552  }
553  printf("Used codec: %i\n", usedCodec);
554  printf("Payload type: %i\n", payloadType);
555
556  NetEQTest_init_coders(usedCodec, packet_size, bitrate, fs, useVAD,
557                        numChannels);
558
559  /* write file header */
560  // fprintf(out_file, "#!RTPencode%s\n", "1.0");
561  fprintf(out_file, "#!rtpplay%s \n",
562          "1.0");               // this is the string that rtpplay needs
563  uint32_t dummy_variable = 0;  // should be converted to network endian format,
564                                // but does not matter when 0
565  if (fwrite(&dummy_variable, 4, 1, out_file) != 1) {
566    return -1;
567  }
568  if (fwrite(&dummy_variable, 4, 1, out_file) != 1) {
569    return -1;
570  }
571  if (fwrite(&dummy_variable, 4, 1, out_file) != 1) {
572    return -1;
573  }
574  if (fwrite(&dummy_variable, 2, 1, out_file) != 1) {
575    return -1;
576  }
577  if (fwrite(&dummy_variable, 2, 1, out_file) != 1) {
578    return -1;
579  }
580
581#ifdef TIMESTAMP_WRAPAROUND
582  timestamp = 0xFFFFFFFF - fs * 10; /* should give wrap-around in 10 seconds */
583#endif
584#if defined(RANDOM_DATA) | defined(RANDOM_PAYLOAD_DATA)
585  srand(RANDOM_SEED);
586#endif
587
588  /* if redundancy is used, the first redundant payload is zero length */
589  red_len[0] = 0;
590
591  /* read first frame */
592  len = fread(org_data, 2, packet_size * numChannels, in_file) / numChannels;
593
594  /* de-interleave if stereo */
595  if (usingStereo) {
596    stereoDeInterleave(org_data, len * numChannels);
597  }
598
599  while (len == packet_size) {
600#ifdef INSERT_DTMF_PACKETS
601    dtmfSent = false;
602
603    if (sendtime >= NTone * DTMF_PACKET_INTERVAL) {
604      if (sendtime < NTone * DTMF_PACKET_INTERVAL + DTMF_DURATION) {
605        // tone has not ended
606        if (DTMFfirst == 1) {
607          DTMFtimestamp = timestamp;  // save this timestamp
608          DTMFfirst = 0;
609        }
610        makeRTPheader(rtp_data, NETEQ_CODEC_AVT_PT, seqNo, DTMFtimestamp, ssrc);
611        enc_len = makeDTMFpayload(
612            &rtp_data[12], NTone % 12, 0, 4,
613            (int)(sendtime - NTone * DTMF_PACKET_INTERVAL) * (fs / 1000) + len);
614      } else {
615        // tone has ended
616        makeRTPheader(rtp_data, NETEQ_CODEC_AVT_PT, seqNo, DTMFtimestamp, ssrc);
617        enc_len = makeDTMFpayload(&rtp_data[12], NTone % 12, 1, 4,
618                                  DTMF_DURATION * (fs / 1000));
619        NTone++;
620        DTMFfirst = 1;
621      }
622
623      /* write RTP packet to file */
624      length = htons(static_cast<unsigned short>(12 + enc_len + 8));
625      plen = htons(static_cast<unsigned short>(12 + enc_len));
626      offset = (uint32_t)sendtime;  //(timestamp/(fs/1000));
627      offset = htonl(offset);
628      if (fwrite(&length, 2, 1, out_file) != 1) {
629        return -1;
630      }
631      if (fwrite(&plen, 2, 1, out_file) != 1) {
632        return -1;
633      }
634      if (fwrite(&offset, 4, 1, out_file) != 1) {
635        return -1;
636      }
637      if (fwrite(rtp_data, 12 + enc_len, 1, out_file) != 1) {
638        return -1;
639      }
640
641      dtmfSent = true;
642    }
643#endif
644
645#ifdef NO_DTMF_OVERDUB
646    /* If DTMF is sent, we should not send any speech packets during the same
647     * time */
648    if (dtmfSent) {
649      enc_len = 0;
650    } else {
651#endif
652      /* encode frame */
653      enc_len =
654          NetEQTest_encode(usedCodec, org_data, packet_size, &rtp_data[12], fs,
655                           &vad, useVAD, bitrate, numChannels);
656      if (enc_len == -1) {
657        printf("Error encoding frame\n");
658        exit(0);
659      }
660
661      if (usingStereo && stereoMode != STEREO_MODE_FRAME && vad == 1) {
662        // interleave the encoded payload for sample-based codecs (not for CNG)
663        stereoInterleave(&rtp_data[12], enc_len, stereoMode);
664      }
665#ifdef NO_DTMF_OVERDUB
666    }
667#endif
668
669    if (enc_len > 0 &&
670        (sendtime <= STOPSENDTIME || sendtime > RESTARTSENDTIME)) {
671      if (useRed) {
672        if (red_len[0] > 0) {
673          memmove(&rtp_data[RTPheaderLen + red_len[0]], &rtp_data[12], enc_len);
674          memcpy(&rtp_data[RTPheaderLen], red_data, red_len[0]);
675
676          red_len[1] = static_cast<uint16_t>(enc_len);
677          red_TS[1] = timestamp;
678          if (vad)
679            red_PT[1] = payloadType;
680          else
681            red_PT[1] = NETEQ_CODEC_CN_PT;
682
683          makeRedundantHeader(rtp_data, red_PT, 2, red_TS, red_len, seqNo++,
684                              ssrc);
685
686          enc_len += red_len[0] + RTPheaderLen - 12;
687        } else {  // do not use redundancy payload for this packet, i.e., only
688                  // last payload
689          memmove(&rtp_data[RTPheaderLen - 4], &rtp_data[12], enc_len);
690          // memcpy(&rtp_data[RTPheaderLen], red_data, red_len[0]);
691
692          red_len[1] = static_cast<uint16_t>(enc_len);
693          red_TS[1] = timestamp;
694          if (vad)
695            red_PT[1] = payloadType;
696          else
697            red_PT[1] = NETEQ_CODEC_CN_PT;
698
699          makeRedundantHeader(rtp_data, red_PT, 2, red_TS, red_len, seqNo++,
700                              ssrc);
701
702          enc_len += red_len[0] + RTPheaderLen - 4 -
703                     12;  // 4 is length of redundancy header (not used)
704        }
705      } else {
706        /* make RTP header */
707        if (vad)  // regular speech data
708          makeRTPheader(rtp_data, payloadType, seqNo++, timestamp, ssrc);
709        else  // CNG data
710          makeRTPheader(rtp_data, NETEQ_CODEC_CN_PT, seqNo++, timestamp, ssrc);
711      }
712#ifdef MULTIPLE_SAME_TIMESTAMP
713      int mult_pack = 0;
714      do {
715#endif  // MULTIPLE_SAME_TIMESTAMP
716        /* write RTP packet to file */
717        length = htons(static_cast<unsigned short>(12 + enc_len + 8));
718        plen = htons(static_cast<unsigned short>(12 + enc_len));
719        offset = (uint32_t)sendtime;
720        //(timestamp/(fs/1000));
721        offset = htonl(offset);
722        if (fwrite(&length, 2, 1, out_file) != 1) {
723          return -1;
724        }
725        if (fwrite(&plen, 2, 1, out_file) != 1) {
726          return -1;
727        }
728        if (fwrite(&offset, 4, 1, out_file) != 1) {
729          return -1;
730        }
731#ifdef RANDOM_DATA
732        for (int k = 0; k < 12 + enc_len; k++) {
733          rtp_data[k] = rand() + rand();
734        }
735#endif
736#ifdef RANDOM_PAYLOAD_DATA
737        for (int k = 12; k < 12 + enc_len; k++) {
738          rtp_data[k] = rand() + rand();
739        }
740#endif
741        if (fwrite(rtp_data, 12 + enc_len, 1, out_file) != 1) {
742          return -1;
743        }
744#ifdef MULTIPLE_SAME_TIMESTAMP
745      } while ((seqNo % REPEAT_PACKET_DISTANCE == 0) &&
746               (mult_pack++ < REPEAT_PACKET_COUNT));
747#endif  // MULTIPLE_SAME_TIMESTAMP
748
749#ifdef INSERT_OLD_PACKETS
750      if (packet_age >= OLD_PACKET * fs) {
751        if (!first_old_packet) {
752          // send the old packet
753          if (fwrite(&old_length, 2, 1, out_file) != 1) {
754            return -1;
755          }
756          if (fwrite(&old_plen, 2, 1, out_file) != 1) {
757            return -1;
758          }
759          if (fwrite(&offset, 4, 1, out_file) != 1) {
760            return -1;
761          }
762          if (fwrite(old_rtp_data, 12 + old_enc_len, 1, out_file) != 1) {
763            return -1;
764          }
765        }
766        // store current packet as old
767        old_length = length;
768        old_plen = plen;
769        memcpy(old_rtp_data, rtp_data, 12 + enc_len);
770        old_enc_len = enc_len;
771        first_old_packet = 0;
772        packet_age = 0;
773      }
774      packet_age += packet_size;
775#endif
776
777      if (useRed) {
778/* move data to redundancy store */
779#ifdef CODEC_ISAC
780        if (usedCodec == webrtc::kDecoderISAC) {
781          assert(!usingStereo);  // Cannot handle stereo yet
782          red_len[0] = WebRtcIsac_GetRedPayload(ISAC_inst[0], red_data);
783        } else {
784#endif
785          memcpy(red_data, &rtp_data[RTPheaderLen + red_len[0]], enc_len);
786          red_len[0] = red_len[1];
787#ifdef CODEC_ISAC
788        }
789#endif
790        red_TS[0] = red_TS[1];
791        red_PT[0] = red_PT[1];
792      }
793    }
794
795    /* read next frame */
796    len = fread(org_data, 2, packet_size * numChannels, in_file) / numChannels;
797    /* de-interleave if stereo */
798    if (usingStereo) {
799      stereoDeInterleave(org_data, len * numChannels);
800    }
801
802    if (payloadType == NETEQ_CODEC_G722_PT)
803      timestamp += len >> 1;
804    else
805      timestamp += len;
806
807    sendtime += (double)len / (fs / 1000);
808  }
809
810  NetEQTest_free_coders(usedCodec, numChannels);
811  fclose(in_file);
812  fclose(out_file);
813  printf("Done!\n");
814
815  return (0);
816}
817
818/****************/
819/* Subfunctions */
820/****************/
821
822void NetEQTest_GetCodec_and_PT(char* name,
823                               webrtc::NetEqDecoder* codec,
824                               int* PT,
825                               int frameLen,
826                               int* fs,
827                               int* bitrate,
828                               int* useRed) {
829  *bitrate = 0; /* Default bitrate setting */
830  *useRed = 0;  /* Default no redundancy */
831
832  if (!strcmp(name, "pcmu")) {
833    *codec = webrtc::kDecoderPCMu;
834    *PT = NETEQ_CODEC_PCMU_PT;
835    *fs = 8000;
836  } else if (!strcmp(name, "pcma")) {
837    *codec = webrtc::kDecoderPCMa;
838    *PT = NETEQ_CODEC_PCMA_PT;
839    *fs = 8000;
840  } else if (!strcmp(name, "pcm16b")) {
841    *codec = webrtc::kDecoderPCM16B;
842    *PT = NETEQ_CODEC_PCM16B_PT;
843    *fs = 8000;
844  } else if (!strcmp(name, "pcm16b_wb")) {
845    *codec = webrtc::kDecoderPCM16Bwb;
846    *PT = NETEQ_CODEC_PCM16B_WB_PT;
847    *fs = 16000;
848  } else if (!strcmp(name, "pcm16b_swb32")) {
849    *codec = webrtc::kDecoderPCM16Bswb32kHz;
850    *PT = NETEQ_CODEC_PCM16B_SWB32KHZ_PT;
851    *fs = 32000;
852  } else if (!strcmp(name, "pcm16b_swb48")) {
853    *codec = webrtc::kDecoderPCM16Bswb48kHz;
854    *PT = NETEQ_CODEC_PCM16B_SWB48KHZ_PT;
855    *fs = 48000;
856  } else if (!strcmp(name, "g722")) {
857    *codec = webrtc::kDecoderG722;
858    *PT = NETEQ_CODEC_G722_PT;
859    *fs = 16000;
860  } else if ((!strcmp(name, "ilbc")) &&
861             ((frameLen % 240 == 0) || (frameLen % 160 == 0))) {
862    *fs = 8000;
863    *codec = webrtc::kDecoderILBC;
864    *PT = NETEQ_CODEC_ILBC_PT;
865  } else if (!strcmp(name, "isac")) {
866    *fs = 16000;
867    *codec = webrtc::kDecoderISAC;
868    *PT = NETEQ_CODEC_ISAC_PT;
869  } else if (!strcmp(name, "isacswb")) {
870    *fs = 32000;
871    *codec = webrtc::kDecoderISACswb;
872    *PT = NETEQ_CODEC_ISACSWB_PT;
873  } else if (!strcmp(name, "red_pcm")) {
874    *codec = webrtc::kDecoderPCMa;
875    *PT = NETEQ_CODEC_PCMA_PT; /* this will be the PT for the sub-headers */
876    *fs = 8000;
877    *useRed = 1;
878  } else if (!strcmp(name, "red_isac")) {
879    *codec = webrtc::kDecoderISAC;
880    *PT = NETEQ_CODEC_ISAC_PT; /* this will be the PT for the sub-headers */
881    *fs = 16000;
882    *useRed = 1;
883  } else {
884    printf("Error: Not a supported codec (%s)\n", name);
885    exit(0);
886  }
887}
888
889int NetEQTest_init_coders(webrtc::NetEqDecoder coder,
890                          int enc_frameSize,
891                          int bitrate,
892                          int sampfreq,
893                          int vad,
894                          int numChannels) {
895  int ok = 0;
896
897  for (int k = 0; k < numChannels; k++) {
898    VAD_inst[k] = WebRtcVad_Create();
899    if (!VAD_inst[k]) {
900      printf("Error: Couldn't allocate memory for VAD instance\n");
901      exit(0);
902    }
903    ok = WebRtcVad_Init(VAD_inst[k]);
904    if (ok == -1) {
905      printf("Error: Initialization of VAD struct failed\n");
906      exit(0);
907    }
908
909#if (defined(CODEC_CNGCODEC8) || defined(CODEC_CNGCODEC16) || \
910     defined(CODEC_CNGCODEC32) || defined(CODEC_CNGCODEC48))
911    ok = WebRtcCng_CreateEnc(&CNGenc_inst[k]);
912    if (ok != 0) {
913      printf("Error: Couldn't allocate memory for CNG encoding instance\n");
914      exit(0);
915    }
916    if (sampfreq <= 16000) {
917      ok = WebRtcCng_InitEnc(CNGenc_inst[k], sampfreq, 200, 5);
918      if (ok == -1) {
919        printf("Error: Initialization of CNG struct failed. Error code %d\n",
920               WebRtcCng_GetErrorCodeEnc(CNGenc_inst[k]));
921        exit(0);
922      }
923    }
924#endif
925
926    switch (coder) {
927#ifdef CODEC_PCM16B
928      case webrtc::kDecoderPCM16B:
929#endif
930#ifdef CODEC_PCM16B_WB
931      case webrtc::kDecoderPCM16Bwb:
932#endif
933#ifdef CODEC_PCM16B_32KHZ
934      case webrtc::kDecoderPCM16Bswb32kHz:
935#endif
936#ifdef CODEC_PCM16B_48KHZ
937      case webrtc::kDecoderPCM16Bswb48kHz:
938#endif
939#ifdef CODEC_G711
940      case webrtc::kDecoderPCMu:
941      case webrtc::kDecoderPCMa:
942#endif
943        // do nothing
944        break;
945#ifdef CODEC_G729
946      case webrtc::kDecoderG729:
947        if (sampfreq == 8000) {
948          if ((enc_frameSize == 80) || (enc_frameSize == 160) ||
949              (enc_frameSize == 240) || (enc_frameSize == 320) ||
950              (enc_frameSize == 400) || (enc_frameSize == 480)) {
951            ok = WebRtcG729_CreateEnc(&G729enc_inst[k]);
952            if (ok != 0) {
953              printf("Error: Couldn't allocate memory for G729 encoding "
954                     "instance\n");
955              exit(0);
956            }
957          } else {
958            printf("\nError: g729 only supports 10, 20, 30, 40, 50 or 60 "
959                   "ms!!\n\n");
960            exit(0);
961          }
962          WebRtcG729_EncoderInit(G729enc_inst[k], vad);
963          if ((vad == 1) && (enc_frameSize != 80)) {
964            printf("\nError - This simulation only supports VAD for G729 at "
965                   "10ms packets (not %dms)\n", (enc_frameSize >> 3));
966          }
967        } else {
968          printf("\nError - g729 is only developed for 8kHz \n");
969          exit(0);
970        }
971        break;
972#endif
973#ifdef CODEC_G729_1
974      case webrtc::kDecoderG729_1:
975        if (sampfreq == 16000) {
976          if ((enc_frameSize == 320) || (enc_frameSize == 640) ||
977              (enc_frameSize == 960)) {
978            ok = WebRtcG7291_Create(&G729_1_inst[k]);
979            if (ok != 0) {
980              printf("Error: Couldn't allocate memory for G.729.1 codec "
981                     "instance\n");
982              exit(0);
983            }
984          } else {
985            printf("\nError: G.729.1 only supports 20, 40 or 60 ms!!\n\n");
986            exit(0);
987          }
988          if (!(((bitrate >= 12000) && (bitrate <= 32000) &&
989                 (bitrate % 2000 == 0)) ||
990                (bitrate == 8000))) {
991            /* must be 8, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, or 32 kbps */
992            printf("\nError: G.729.1 bitrate must be 8000 or 12000--32000 in "
993                   "steps of 2000 bps\n");
994            exit(0);
995          }
996          WebRtcG7291_EncoderInit(G729_1_inst[k], bitrate, 0 /* flag8kHz*/,
997                                  0 /*flagG729mode*/);
998        } else {
999          printf("\nError - G.729.1 input is always 16 kHz \n");
1000          exit(0);
1001        }
1002        break;
1003#endif
1004#ifdef CODEC_SPEEX_8
1005      case webrtc::kDecoderSPEEX_8:
1006        if (sampfreq == 8000) {
1007          if ((enc_frameSize == 160) || (enc_frameSize == 320) ||
1008              (enc_frameSize == 480)) {
1009            ok = WebRtcSpeex_CreateEnc(&SPEEX8enc_inst[k], sampfreq);
1010            if (ok != 0) {
1011              printf("Error: Couldn't allocate memory for Speex encoding "
1012                     "instance\n");
1013              exit(0);
1014            }
1015          } else {
1016            printf("\nError: Speex only supports 20, 40, and 60 ms!!\n\n");
1017            exit(0);
1018          }
1019          if ((vad == 1) && (enc_frameSize != 160)) {
1020            printf("\nError - This simulation only supports VAD for Speex at "
1021                   "20ms packets (not %dms)\n",
1022                (enc_frameSize >> 3));
1023            vad = 0;
1024          }
1025          ok = WebRtcSpeex_EncoderInit(SPEEX8enc_inst[k], 0 /*vbr*/,
1026                                       3 /*complexity*/, vad);
1027          if (ok != 0)
1028            exit(0);
1029        } else {
1030          printf("\nError - Speex8 called with sample frequency other than 8 "
1031                 "kHz.\n\n");
1032        }
1033        break;
1034#endif
1035#ifdef CODEC_SPEEX_16
1036      case webrtc::kDecoderSPEEX_16:
1037        if (sampfreq == 16000) {
1038          if ((enc_frameSize == 320) || (enc_frameSize == 640) ||
1039              (enc_frameSize == 960)) {
1040            ok = WebRtcSpeex_CreateEnc(&SPEEX16enc_inst[k], sampfreq);
1041            if (ok != 0) {
1042              printf("Error: Couldn't allocate memory for Speex encoding "
1043                     "instance\n");
1044              exit(0);
1045            }
1046          } else {
1047            printf("\nError: Speex only supports 20, 40, and 60 ms!!\n\n");
1048            exit(0);
1049          }
1050          if ((vad == 1) && (enc_frameSize != 320)) {
1051            printf("\nError - This simulation only supports VAD for Speex at "
1052                   "20ms packets (not %dms)\n",
1053                (enc_frameSize >> 4));
1054            vad = 0;
1055          }
1056          ok = WebRtcSpeex_EncoderInit(SPEEX16enc_inst[k], 0 /*vbr*/,
1057                                       3 /*complexity*/, vad);
1058          if (ok != 0)
1059            exit(0);
1060        } else {
1061          printf("\nError - Speex16 called with sample frequency other than 16 "
1062                 "kHz.\n\n");
1063        }
1064        break;
1065#endif
1066
1067#ifdef CODEC_G722_1_16
1068      case webrtc::kDecoderG722_1_16:
1069        if (sampfreq == 16000) {
1070          ok = WebRtcG7221_CreateEnc16(&G722_1_16enc_inst[k]);
1071          if (ok != 0) {
1072            printf("Error: Couldn't allocate memory for G.722.1 instance\n");
1073            exit(0);
1074          }
1075          if (enc_frameSize == 320) {
1076          } else {
1077            printf("\nError: G722.1 only supports 20 ms!!\n\n");
1078            exit(0);
1079          }
1080          WebRtcG7221_EncoderInit16((G722_1_16_encinst_t*)G722_1_16enc_inst[k]);
1081        } else {
1082          printf("\nError - G722.1 is only developed for 16kHz \n");
1083          exit(0);
1084        }
1085        break;
1086#endif
1087#ifdef CODEC_G722_1_24
1088      case webrtc::kDecoderG722_1_24:
1089        if (sampfreq == 16000) {
1090          ok = WebRtcG7221_CreateEnc24(&G722_1_24enc_inst[k]);
1091          if (ok != 0) {
1092            printf("Error: Couldn't allocate memory for G.722.1 instance\n");
1093            exit(0);
1094          }
1095          if (enc_frameSize == 320) {
1096          } else {
1097            printf("\nError: G722.1 only supports 20 ms!!\n\n");
1098            exit(0);
1099          }
1100          WebRtcG7221_EncoderInit24((G722_1_24_encinst_t*)G722_1_24enc_inst[k]);
1101        } else {
1102          printf("\nError - G722.1 is only developed for 16kHz \n");
1103          exit(0);
1104        }
1105        break;
1106#endif
1107#ifdef CODEC_G722_1_32
1108      case webrtc::kDecoderG722_1_32:
1109        if (sampfreq == 16000) {
1110          ok = WebRtcG7221_CreateEnc32(&G722_1_32enc_inst[k]);
1111          if (ok != 0) {
1112            printf("Error: Couldn't allocate memory for G.722.1 instance\n");
1113            exit(0);
1114          }
1115          if (enc_frameSize == 320) {
1116          } else {
1117            printf("\nError: G722.1 only supports 20 ms!!\n\n");
1118            exit(0);
1119          }
1120          WebRtcG7221_EncoderInit32((G722_1_32_encinst_t*)G722_1_32enc_inst[k]);
1121        } else {
1122          printf("\nError - G722.1 is only developed for 16kHz \n");
1123          exit(0);
1124        }
1125        break;
1126#endif
1127#ifdef CODEC_G722_1C_24
1128      case webrtc::kDecoderG722_1C_24:
1129        if (sampfreq == 32000) {
1130          ok = WebRtcG7221C_CreateEnc24(&G722_1C_24enc_inst[k]);
1131          if (ok != 0) {
1132            printf("Error: Couldn't allocate memory for G.722.1C instance\n");
1133            exit(0);
1134          }
1135          if (enc_frameSize == 640) {
1136          } else {
1137            printf("\nError: G722.1 C only supports 20 ms!!\n\n");
1138            exit(0);
1139          }
1140          WebRtcG7221C_EncoderInit24(
1141              (G722_1C_24_encinst_t*)G722_1C_24enc_inst[k]);
1142        } else {
1143          printf("\nError - G722.1 C is only developed for 32kHz \n");
1144          exit(0);
1145        }
1146        break;
1147#endif
1148#ifdef CODEC_G722_1C_32
1149      case webrtc::kDecoderG722_1C_32:
1150        if (sampfreq == 32000) {
1151          ok = WebRtcG7221C_CreateEnc32(&G722_1C_32enc_inst[k]);
1152          if (ok != 0) {
1153            printf("Error: Couldn't allocate memory for G.722.1C instance\n");
1154            exit(0);
1155          }
1156          if (enc_frameSize == 640) {
1157          } else {
1158            printf("\nError: G722.1 C only supports 20 ms!!\n\n");
1159            exit(0);
1160          }
1161          WebRtcG7221C_EncoderInit32(
1162              (G722_1C_32_encinst_t*)G722_1C_32enc_inst[k]);
1163        } else {
1164          printf("\nError - G722.1 C is only developed for 32kHz \n");
1165          exit(0);
1166        }
1167        break;
1168#endif
1169#ifdef CODEC_G722_1C_48
1170      case webrtc::kDecoderG722_1C_48:
1171        if (sampfreq == 32000) {
1172          ok = WebRtcG7221C_CreateEnc48(&G722_1C_48enc_inst[k]);
1173          if (ok != 0) {
1174            printf("Error: Couldn't allocate memory for G.722.1C instance\n");
1175            exit(0);
1176          }
1177          if (enc_frameSize == 640) {
1178          } else {
1179            printf("\nError: G722.1 C only supports 20 ms!!\n\n");
1180            exit(0);
1181          }
1182          WebRtcG7221C_EncoderInit48(
1183              (G722_1C_48_encinst_t*)G722_1C_48enc_inst[k]);
1184        } else {
1185          printf("\nError - G722.1 C is only developed for 32kHz \n");
1186          exit(0);
1187        }
1188        break;
1189#endif
1190#ifdef CODEC_G722
1191      case webrtc::kDecoderG722:
1192        if (sampfreq == 16000) {
1193          if (enc_frameSize % 2 == 0) {
1194          } else {
1195            printf(
1196                "\nError - g722 frames must have an even number of "
1197                "enc_frameSize\n");
1198            exit(0);
1199          }
1200          WebRtcG722_CreateEncoder(&g722EncState[k]);
1201          WebRtcG722_EncoderInit(g722EncState[k]);
1202        } else {
1203          printf("\nError - g722 is only developed for 16kHz \n");
1204          exit(0);
1205        }
1206        break;
1207#endif
1208#ifdef CODEC_AMR
1209      case webrtc::kDecoderAMR:
1210        if (sampfreq == 8000) {
1211          ok = WebRtcAmr_CreateEnc(&AMRenc_inst[k]);
1212          if (ok != 0) {
1213            printf(
1214                "Error: Couldn't allocate memory for AMR encoding instance\n");
1215            exit(0);
1216          }
1217          if ((enc_frameSize == 160) || (enc_frameSize == 320) ||
1218              (enc_frameSize == 480)) {
1219          } else {
1220            printf("\nError - AMR must have a multiple of 160 enc_frameSize\n");
1221            exit(0);
1222          }
1223          WebRtcAmr_EncoderInit(AMRenc_inst[k], vad);
1224          WebRtcAmr_EncodeBitmode(AMRenc_inst[k], AMRBandwidthEfficient);
1225          AMR_bitrate = bitrate;
1226        } else {
1227          printf("\nError - AMR is only developed for 8kHz \n");
1228          exit(0);
1229        }
1230        break;
1231#endif
1232#ifdef CODEC_AMRWB
1233      case webrtc::kDecoderAMRWB:
1234        if (sampfreq == 16000) {
1235          ok = WebRtcAmrWb_CreateEnc(&AMRWBenc_inst[k]);
1236          if (ok != 0) {
1237            printf("Error: Couldn't allocate memory for AMRWB encoding "
1238                   "instance\n");
1239            exit(0);
1240          }
1241          if (((enc_frameSize / 320) < 0) || ((enc_frameSize / 320) > 3) ||
1242              ((enc_frameSize % 320) != 0)) {
1243            printf("\nError - AMRwb must have frameSize of 20, 40 or 60ms\n");
1244            exit(0);
1245          }
1246          WebRtcAmrWb_EncoderInit(AMRWBenc_inst[k], vad);
1247          if (bitrate == 7000) {
1248            AMRWB_bitrate = AMRWB_MODE_7k;
1249          } else if (bitrate == 9000) {
1250            AMRWB_bitrate = AMRWB_MODE_9k;
1251          } else if (bitrate == 12000) {
1252            AMRWB_bitrate = AMRWB_MODE_12k;
1253          } else if (bitrate == 14000) {
1254            AMRWB_bitrate = AMRWB_MODE_14k;
1255          } else if (bitrate == 16000) {
1256            AMRWB_bitrate = AMRWB_MODE_16k;
1257          } else if (bitrate == 18000) {
1258            AMRWB_bitrate = AMRWB_MODE_18k;
1259          } else if (bitrate == 20000) {
1260            AMRWB_bitrate = AMRWB_MODE_20k;
1261          } else if (bitrate == 23000) {
1262            AMRWB_bitrate = AMRWB_MODE_23k;
1263          } else if (bitrate == 24000) {
1264            AMRWB_bitrate = AMRWB_MODE_24k;
1265          }
1266          WebRtcAmrWb_EncodeBitmode(AMRWBenc_inst[k], AMRBandwidthEfficient);
1267
1268        } else {
1269          printf("\nError - AMRwb is only developed for 16kHz \n");
1270          exit(0);
1271        }
1272        break;
1273#endif
1274#ifdef CODEC_ILBC
1275      case webrtc::kDecoderILBC:
1276        if (sampfreq == 8000) {
1277          ok = WebRtcIlbcfix_EncoderCreate(&iLBCenc_inst[k]);
1278          if (ok != 0) {
1279            printf("Error: Couldn't allocate memory for iLBC encoding "
1280                   "instance\n");
1281            exit(0);
1282          }
1283          if ((enc_frameSize == 160) || (enc_frameSize == 240) ||
1284              (enc_frameSize == 320) || (enc_frameSize == 480)) {
1285          } else {
1286            printf("\nError - iLBC only supports 160, 240, 320 and 480 "
1287                   "enc_frameSize (20, 30, 40 and 60 ms)\n");
1288            exit(0);
1289          }
1290          if ((enc_frameSize == 160) || (enc_frameSize == 320)) {
1291            /* 20 ms version */
1292            WebRtcIlbcfix_EncoderInit(iLBCenc_inst[k], 20);
1293          } else {
1294            /* 30 ms version */
1295            WebRtcIlbcfix_EncoderInit(iLBCenc_inst[k], 30);
1296          }
1297        } else {
1298          printf("\nError - iLBC is only developed for 8kHz \n");
1299          exit(0);
1300        }
1301        break;
1302#endif
1303#ifdef CODEC_ISAC
1304      case webrtc::kDecoderISAC:
1305        if (sampfreq == 16000) {
1306          ok = WebRtcIsac_Create(&ISAC_inst[k]);
1307          if (ok != 0) {
1308            printf("Error: Couldn't allocate memory for iSAC instance\n");
1309            exit(0);
1310          }
1311          if ((enc_frameSize == 480) || (enc_frameSize == 960)) {
1312          } else {
1313            printf("\nError - iSAC only supports frameSize (30 and 60 ms)\n");
1314            exit(0);
1315          }
1316          WebRtcIsac_EncoderInit(ISAC_inst[k], 1);
1317          if ((bitrate < 10000) || (bitrate > 32000)) {
1318            printf("\nError - iSAC bitrate has to be between 10000 and 32000 "
1319                   "bps (not %i)\n",
1320                bitrate);
1321            exit(0);
1322          }
1323          WebRtcIsac_Control(ISAC_inst[k], bitrate, enc_frameSize >> 4);
1324        } else {
1325          printf("\nError - iSAC only supports 480 or 960 enc_frameSize (30 or "
1326                 "60 ms)\n");
1327          exit(0);
1328        }
1329        break;
1330#endif
1331#ifdef NETEQ_ISACFIX_CODEC
1332      case webrtc::kDecoderISAC:
1333        if (sampfreq == 16000) {
1334          ok = WebRtcIsacfix_Create(&ISAC_inst[k]);
1335          if (ok != 0) {
1336            printf("Error: Couldn't allocate memory for iSAC instance\n");
1337            exit(0);
1338          }
1339          if ((enc_frameSize == 480) || (enc_frameSize == 960)) {
1340          } else {
1341            printf("\nError - iSAC only supports frameSize (30 and 60 ms)\n");
1342            exit(0);
1343          }
1344          WebRtcIsacfix_EncoderInit(ISAC_inst[k], 1);
1345          if ((bitrate < 10000) || (bitrate > 32000)) {
1346            printf("\nError - iSAC bitrate has to be between 10000 and 32000 "
1347                   "bps (not %i)\n", bitrate);
1348            exit(0);
1349          }
1350          WebRtcIsacfix_Control(ISAC_inst[k], bitrate, enc_frameSize >> 4);
1351        } else {
1352          printf("\nError - iSAC only supports 480 or 960 enc_frameSize (30 or "
1353                 "60 ms)\n");
1354          exit(0);
1355        }
1356        break;
1357#endif
1358#ifdef CODEC_ISAC_SWB
1359      case webrtc::kDecoderISACswb:
1360        if (sampfreq == 32000) {
1361          ok = WebRtcIsac_Create(&ISACSWB_inst[k]);
1362          if (ok != 0) {
1363            printf("Error: Couldn't allocate memory for iSAC SWB instance\n");
1364            exit(0);
1365          }
1366          if (enc_frameSize == 960) {
1367          } else {
1368            printf("\nError - iSAC SWB only supports frameSize 30 ms\n");
1369            exit(0);
1370          }
1371          ok = WebRtcIsac_SetEncSampRate(ISACSWB_inst[k], 32000);
1372          if (ok != 0) {
1373            printf("Error: Couldn't set sample rate for iSAC SWB instance\n");
1374            exit(0);
1375          }
1376          WebRtcIsac_EncoderInit(ISACSWB_inst[k], 1);
1377          if ((bitrate < 32000) || (bitrate > 56000)) {
1378            printf("\nError - iSAC SWB bitrate has to be between 32000 and "
1379                   "56000 bps (not %i)\n", bitrate);
1380            exit(0);
1381          }
1382          WebRtcIsac_Control(ISACSWB_inst[k], bitrate, enc_frameSize >> 5);
1383        } else {
1384          printf("\nError - iSAC SWB only supports 960 enc_frameSize (30 "
1385                 "ms)\n");
1386          exit(0);
1387        }
1388        break;
1389#endif
1390#ifdef CODEC_GSMFR
1391      case webrtc::kDecoderGSMFR:
1392        if (sampfreq == 8000) {
1393          ok = WebRtcGSMFR_CreateEnc(&GSMFRenc_inst[k]);
1394          if (ok != 0) {
1395            printf("Error: Couldn't allocate memory for GSM FR encoding "
1396                   "instance\n");
1397            exit(0);
1398          }
1399          if ((enc_frameSize == 160) || (enc_frameSize == 320) ||
1400              (enc_frameSize == 480)) {
1401          } else {
1402            printf("\nError - GSM FR must have a multiple of 160 "
1403                   "enc_frameSize\n");
1404            exit(0);
1405          }
1406          WebRtcGSMFR_EncoderInit(GSMFRenc_inst[k], 0);
1407        } else {
1408          printf("\nError - GSM FR is only developed for 8kHz \n");
1409          exit(0);
1410        }
1411        break;
1412#endif
1413      default:
1414        printf("Error: unknown codec in call to NetEQTest_init_coders.\n");
1415        exit(0);
1416        break;
1417    }
1418
1419    if (ok != 0) {
1420      return (ok);
1421    }
1422  }  // end for
1423
1424  return (0);
1425}
1426
1427int NetEQTest_free_coders(webrtc::NetEqDecoder coder, int numChannels) {
1428  for (int k = 0; k < numChannels; k++) {
1429    WebRtcVad_Free(VAD_inst[k]);
1430#if (defined(CODEC_CNGCODEC8) || defined(CODEC_CNGCODEC16) || \
1431     defined(CODEC_CNGCODEC32) || defined(CODEC_CNGCODEC48))
1432    WebRtcCng_FreeEnc(CNGenc_inst[k]);
1433#endif
1434
1435    switch (coder) {
1436#ifdef CODEC_PCM16B
1437      case webrtc::kDecoderPCM16B:
1438#endif
1439#ifdef CODEC_PCM16B_WB
1440      case webrtc::kDecoderPCM16Bwb:
1441#endif
1442#ifdef CODEC_PCM16B_32KHZ
1443      case webrtc::kDecoderPCM16Bswb32kHz:
1444#endif
1445#ifdef CODEC_PCM16B_48KHZ
1446      case webrtc::kDecoderPCM16Bswb48kHz:
1447#endif
1448#ifdef CODEC_G711
1449      case webrtc::kDecoderPCMu:
1450      case webrtc::kDecoderPCMa:
1451#endif
1452        // do nothing
1453        break;
1454#ifdef CODEC_G729
1455      case webrtc::kDecoderG729:
1456        WebRtcG729_FreeEnc(G729enc_inst[k]);
1457        break;
1458#endif
1459#ifdef CODEC_G729_1
1460      case webrtc::kDecoderG729_1:
1461        WebRtcG7291_Free(G729_1_inst[k]);
1462        break;
1463#endif
1464#ifdef CODEC_SPEEX_8
1465      case webrtc::kDecoderSPEEX_8:
1466        WebRtcSpeex_FreeEnc(SPEEX8enc_inst[k]);
1467        break;
1468#endif
1469#ifdef CODEC_SPEEX_16
1470      case webrtc::kDecoderSPEEX_16:
1471        WebRtcSpeex_FreeEnc(SPEEX16enc_inst[k]);
1472        break;
1473#endif
1474
1475#ifdef CODEC_G722_1_16
1476      case webrtc::kDecoderG722_1_16:
1477        WebRtcG7221_FreeEnc16(G722_1_16enc_inst[k]);
1478        break;
1479#endif
1480#ifdef CODEC_G722_1_24
1481      case webrtc::kDecoderG722_1_24:
1482        WebRtcG7221_FreeEnc24(G722_1_24enc_inst[k]);
1483        break;
1484#endif
1485#ifdef CODEC_G722_1_32
1486      case webrtc::kDecoderG722_1_32:
1487        WebRtcG7221_FreeEnc32(G722_1_32enc_inst[k]);
1488        break;
1489#endif
1490#ifdef CODEC_G722_1C_24
1491      case webrtc::kDecoderG722_1C_24:
1492        WebRtcG7221C_FreeEnc24(G722_1C_24enc_inst[k]);
1493        break;
1494#endif
1495#ifdef CODEC_G722_1C_32
1496      case webrtc::kDecoderG722_1C_32:
1497        WebRtcG7221C_FreeEnc32(G722_1C_32enc_inst[k]);
1498        break;
1499#endif
1500#ifdef CODEC_G722_1C_48
1501      case webrtc::kDecoderG722_1C_48:
1502        WebRtcG7221C_FreeEnc48(G722_1C_48enc_inst[k]);
1503        break;
1504#endif
1505#ifdef CODEC_G722
1506      case webrtc::kDecoderG722:
1507        WebRtcG722_FreeEncoder(g722EncState[k]);
1508        break;
1509#endif
1510#ifdef CODEC_AMR
1511      case webrtc::kDecoderAMR:
1512        WebRtcAmr_FreeEnc(AMRenc_inst[k]);
1513        break;
1514#endif
1515#ifdef CODEC_AMRWB
1516      case webrtc::kDecoderAMRWB:
1517        WebRtcAmrWb_FreeEnc(AMRWBenc_inst[k]);
1518        break;
1519#endif
1520#ifdef CODEC_ILBC
1521      case webrtc::kDecoderILBC:
1522        WebRtcIlbcfix_EncoderFree(iLBCenc_inst[k]);
1523        break;
1524#endif
1525#ifdef CODEC_ISAC
1526      case webrtc::kDecoderISAC:
1527        WebRtcIsac_Free(ISAC_inst[k]);
1528        break;
1529#endif
1530#ifdef NETEQ_ISACFIX_CODEC
1531      case webrtc::kDecoderISAC:
1532        WebRtcIsacfix_Free(ISAC_inst[k]);
1533        break;
1534#endif
1535#ifdef CODEC_ISAC_SWB
1536      case webrtc::kDecoderISACswb:
1537        WebRtcIsac_Free(ISACSWB_inst[k]);
1538        break;
1539#endif
1540#ifdef CODEC_GSMFR
1541      case webrtc::kDecoderGSMFR:
1542        WebRtcGSMFR_FreeEnc(GSMFRenc_inst[k]);
1543        break;
1544#endif
1545      default:
1546        printf("Error: unknown codec in call to NetEQTest_init_coders.\n");
1547        exit(0);
1548        break;
1549    }
1550  }
1551
1552  return (0);
1553}
1554
1555int NetEQTest_encode(int coder,
1556                     int16_t* indata,
1557                     int frameLen,
1558                     unsigned char* encoded,
1559                     int sampleRate,
1560                     int* vad,
1561                     int useVAD,
1562                     int bitrate,
1563                     int numChannels) {
1564  short cdlen = 0;
1565  int16_t* tempdata;
1566  static int first_cng = 1;
1567  int16_t tempLen;
1568
1569  *vad = 1;
1570
1571  // check VAD first
1572  if (useVAD) {
1573    *vad = 0;
1574
1575    for (int k = 0; k < numChannels; k++) {
1576      tempLen = frameLen;
1577      tempdata = &indata[k * frameLen];
1578      int localVad = 0;
1579      /* Partition the signal and test each chunk for VAD.
1580      All chunks must be VAD=0 to produce a total VAD=0. */
1581      while (tempLen >= 10 * sampleRate / 1000) {
1582        if ((tempLen % 30 * sampleRate / 1000) ==
1583            0) {  // tempLen is multiple of 30ms
1584          localVad |= WebRtcVad_Process(VAD_inst[k], sampleRate, tempdata,
1585                                        30 * sampleRate / 1000);
1586          tempdata += 30 * sampleRate / 1000;
1587          tempLen -= 30 * sampleRate / 1000;
1588        } else if (tempLen >= 20 * sampleRate / 1000) {  // tempLen >= 20ms
1589          localVad |= WebRtcVad_Process(VAD_inst[k], sampleRate, tempdata,
1590                                        20 * sampleRate / 1000);
1591          tempdata += 20 * sampleRate / 1000;
1592          tempLen -= 20 * sampleRate / 1000;
1593        } else {  // use 10ms
1594          localVad |= WebRtcVad_Process(VAD_inst[k], sampleRate, tempdata,
1595                                        10 * sampleRate / 1000);
1596          tempdata += 10 * sampleRate / 1000;
1597          tempLen -= 10 * sampleRate / 1000;
1598        }
1599      }
1600
1601      // aggregate all VAD decisions over all channels
1602      *vad |= localVad;
1603    }
1604
1605    if (!*vad) {
1606      // all channels are silent
1607      cdlen = 0;
1608      for (int k = 0; k < numChannels; k++) {
1609        WebRtcCng_Encode(CNGenc_inst[k], &indata[k * frameLen],
1610                         (frameLen <= 640 ? frameLen : 640) /* max 640 */,
1611                         encoded, &tempLen, first_cng);
1612        encoded += tempLen;
1613        cdlen += tempLen;
1614      }
1615      *vad = 0;
1616      first_cng = 0;
1617      return (cdlen);
1618    }
1619  }
1620
1621  // loop over all channels
1622  int totalLen = 0;
1623
1624  for (int k = 0; k < numChannels; k++) {
1625    /* Encode with the selected coder type */
1626    if (coder == webrtc::kDecoderPCMu) { /*g711 u-law */
1627#ifdef CODEC_G711
1628      cdlen = WebRtcG711_EncodeU(indata, frameLen, encoded);
1629#endif
1630    } else if (coder == webrtc::kDecoderPCMa) { /*g711 A-law */
1631#ifdef CODEC_G711
1632      cdlen = WebRtcG711_EncodeA(indata, frameLen, encoded);
1633    }
1634#endif
1635#ifdef CODEC_PCM16B
1636    else if ((coder == webrtc::kDecoderPCM16B) ||
1637             (coder == webrtc::kDecoderPCM16Bwb) ||
1638             (coder == webrtc::kDecoderPCM16Bswb32kHz) ||
1639             (coder == webrtc::
1640                           kDecoderPCM16Bswb48kHz)) { /*pcm16b (8kHz, 16kHz,
1641                                                         32kHz or 48kHz) */
1642      cdlen = WebRtcPcm16b_Encode(indata, frameLen, encoded);
1643    }
1644#endif
1645#ifdef CODEC_G722
1646    else if (coder == webrtc::kDecoderG722) { /*g722 */
1647      cdlen = WebRtcG722_Encode(g722EncState[k], indata, frameLen, encoded);
1648      assert(cdlen == frameLen >> 1);
1649    }
1650#endif
1651#ifdef CODEC_ILBC
1652    else if (coder == webrtc::kDecoderILBC) { /*iLBC */
1653      cdlen = WebRtcIlbcfix_Encode(iLBCenc_inst[k], indata, frameLen, encoded);
1654    }
1655#endif
1656#if (defined(CODEC_ISAC) || \
1657     defined(NETEQ_ISACFIX_CODEC))            // TODO(hlundin): remove all
1658                                              // NETEQ_ISACFIX_CODEC
1659    else if (coder == webrtc::kDecoderISAC) { /*iSAC */
1660      int noOfCalls = 0;
1661      cdlen = 0;
1662      while (cdlen <= 0) {
1663#ifdef CODEC_ISAC /* floating point */
1664        cdlen =
1665            WebRtcIsac_Encode(ISAC_inst[k], &indata[noOfCalls * 160], encoded);
1666#else /* fixed point */
1667        cdlen = WebRtcIsacfix_Encode(ISAC_inst[k], &indata[noOfCalls * 160],
1668                                     encoded);
1669#endif
1670        noOfCalls++;
1671      }
1672    }
1673#endif
1674#ifdef CODEC_ISAC_SWB
1675    else if (coder == webrtc::kDecoderISACswb) { /* iSAC SWB */
1676      int noOfCalls = 0;
1677      cdlen = 0;
1678      while (cdlen <= 0) {
1679        cdlen = WebRtcIsac_Encode(ISACSWB_inst[k], &indata[noOfCalls * 320],
1680                                  encoded);
1681        noOfCalls++;
1682      }
1683    }
1684#endif
1685    indata += frameLen;
1686    encoded += cdlen;
1687    totalLen += cdlen;
1688
1689  }  // end for
1690
1691  first_cng = 1;
1692  return (totalLen);
1693}
1694
1695void makeRTPheader(unsigned char* rtp_data,
1696                   int payloadType,
1697                   int seqNo,
1698                   uint32_t timestamp,
1699                   uint32_t ssrc) {
1700  rtp_data[0] = 0x80;
1701  rtp_data[1] = payloadType & 0xFF;
1702  rtp_data[2] = (seqNo >> 8) & 0xFF;
1703  rtp_data[3] = seqNo & 0xFF;
1704  rtp_data[4] = timestamp >> 24;
1705  rtp_data[5] = (timestamp >> 16) & 0xFF;
1706  rtp_data[6] = (timestamp >> 8) & 0xFF;
1707  rtp_data[7] = timestamp & 0xFF;
1708  rtp_data[8] = ssrc >> 24;
1709  rtp_data[9] = (ssrc >> 16) & 0xFF;
1710  rtp_data[10] = (ssrc >> 8) & 0xFF;
1711  rtp_data[11] = ssrc & 0xFF;
1712}
1713
1714int makeRedundantHeader(unsigned char* rtp_data,
1715                        int* payloadType,
1716                        int numPayloads,
1717                        uint32_t* timestamp,
1718                        uint16_t* blockLen,
1719                        int seqNo,
1720                        uint32_t ssrc) {
1721  int i;
1722  unsigned char* rtpPointer;
1723  uint16_t offset;
1724
1725  /* first create "standard" RTP header */
1726  makeRTPheader(rtp_data, NETEQ_CODEC_RED_PT, seqNo, timestamp[numPayloads - 1],
1727                ssrc);
1728
1729  rtpPointer = &rtp_data[12];
1730
1731  /* add one sub-header for each redundant payload (not the primary) */
1732  for (i = 0; i < numPayloads - 1; i++) {
1733    if (blockLen[i] > 0) {
1734      offset = static_cast<uint16_t>(timestamp[numPayloads - 1] - timestamp[i]);
1735
1736      // Byte |0|       |1       2     |  3       |
1737      // Bit  |0|1234567|01234567012345|6701234567|
1738      //      |F|payload|   timestamp  |   block  |
1739      //      | |  type |    offset    |  length  |
1740      rtpPointer[0] = (payloadType[i] & 0x7F) | 0x80;
1741      rtpPointer[1] = (offset >> 6) & 0xFF;
1742      rtpPointer[2] = ((offset & 0x3F) << 2) | ((blockLen[i] >> 8) & 0x03);
1743      rtpPointer[3] = blockLen[i] & 0xFF;
1744
1745      rtpPointer += 4;
1746    }
1747  }
1748
1749  // Bit  |0|1234567|
1750  //      |0|payload|
1751  //      | |  type |
1752  rtpPointer[0] = payloadType[numPayloads - 1] & 0x7F;
1753  ++rtpPointer;
1754
1755  return rtpPointer - rtp_data;  // length of header in bytes
1756}
1757
1758int makeDTMFpayload(unsigned char* payload_data,
1759                    int Event,
1760                    int End,
1761                    int Volume,
1762                    int Duration) {
1763  unsigned char E, R, V;
1764  R = 0;
1765  V = (unsigned char)Volume;
1766  if (End == 0) {
1767    E = 0x00;
1768  } else {
1769    E = 0x80;
1770  }
1771  payload_data[0] = (unsigned char)Event;
1772  payload_data[1] = (unsigned char)(E | R | V);
1773  // Duration equals 8 times time_ms, default is 8000 Hz.
1774  payload_data[2] = (unsigned char)((Duration >> 8) & 0xFF);
1775  payload_data[3] = (unsigned char)(Duration & 0xFF);
1776  return (4);
1777}
1778
1779void stereoDeInterleave(int16_t* audioSamples, int numSamples) {
1780  int16_t* tempVec;
1781  int16_t* readPtr, *writeL, *writeR;
1782
1783  if (numSamples <= 0)
1784    return;
1785
1786  tempVec = (int16_t*)malloc(sizeof(int16_t) * numSamples);
1787  if (tempVec == NULL) {
1788    printf("Error allocating memory\n");
1789    exit(0);
1790  }
1791
1792  memcpy(tempVec, audioSamples, numSamples * sizeof(int16_t));
1793
1794  writeL = audioSamples;
1795  writeR = &audioSamples[numSamples / 2];
1796  readPtr = tempVec;
1797
1798  for (int k = 0; k < numSamples; k += 2) {
1799    *writeL = *readPtr;
1800    readPtr++;
1801    *writeR = *readPtr;
1802    readPtr++;
1803    writeL++;
1804    writeR++;
1805  }
1806
1807  free(tempVec);
1808}
1809
1810void stereoInterleave(unsigned char* data, int dataLen, int stride) {
1811  unsigned char* ptrL, *ptrR;
1812  unsigned char temp[10];
1813
1814  if (stride > 10) {
1815    exit(0);
1816  }
1817
1818  if (dataLen % 1 != 0) {
1819    // must be even number of samples
1820    printf("Error: cannot interleave odd sample number\n");
1821    exit(0);
1822  }
1823
1824  ptrL = data + stride;
1825  ptrR = &data[dataLen / 2];
1826
1827  while (ptrL < ptrR) {
1828    // copy from right pointer to temp
1829    memcpy(temp, ptrR, stride);
1830
1831    // shift data between pointers
1832    memmove(ptrL + stride, ptrL, ptrR - ptrL);
1833
1834    // copy from temp to left pointer
1835    memcpy(ptrL, temp, stride);
1836
1837    // advance pointers
1838    ptrL += stride * 2;
1839    ptrR += stride;
1840  }
1841}
1842