opus_encoder.c 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537
  1. /* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited
  2. Written by Jean-Marc Valin and Koen Vos */
  3. /*
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions
  6. are met:
  7. - Redistributions of source code must retain the above copyright
  8. notice, this list of conditions and the following disclaimer.
  9. - Redistributions in binary form must reproduce the above copyright
  10. notice, this list of conditions and the following disclaimer in the
  11. documentation and/or other materials provided with the distribution.
  12. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  13. ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  14. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  15. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
  16. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  17. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  18. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  19. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  22. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. #ifdef HAVE_CONFIG_H
  25. #include "config.h"
  26. #endif
  27. #include <stdarg.h>
  28. #include "celt.h"
  29. #include "entenc.h"
  30. #include "modes.h"
  31. #include "API.h"
  32. #include "stack_alloc.h"
  33. #include "float_cast.h"
  34. #include "opus.h"
  35. #include "arch.h"
  36. #include "pitch.h"
  37. #include "opus_private.h"
  38. #include "os_support.h"
  39. #include "cpu_support.h"
  40. #include "analysis.h"
  41. #include "mathops.h"
  42. #include "tuning_parameters.h"
  43. #ifdef FIXED_POINT
  44. #include "fixed/structs_FIX.h"
  45. #else
  46. #include "float/structs_FLP.h"
  47. #endif
  48. #define MAX_ENCODER_BUFFER 480
  49. typedef struct {
  50. opus_val32 XX, XY, YY;
  51. opus_val16 smoothed_width;
  52. opus_val16 max_follower;
  53. } StereoWidthState;
  54. struct OpusEncoder {
  55. int celt_enc_offset;
  56. int silk_enc_offset;
  57. silk_EncControlStruct silk_mode;
  58. int application;
  59. int channels;
  60. int delay_compensation;
  61. int force_channels;
  62. int signal_type;
  63. int user_bandwidth;
  64. int max_bandwidth;
  65. int user_forced_mode;
  66. int voice_ratio;
  67. opus_int32 Fs;
  68. int use_vbr;
  69. int vbr_constraint;
  70. int variable_duration;
  71. opus_int32 bitrate_bps;
  72. opus_int32 user_bitrate_bps;
  73. int lsb_depth;
  74. int encoder_buffer;
  75. int lfe;
  76. int arch;
  77. #ifndef DISABLE_FLOAT_API
  78. TonalityAnalysisState analysis;
  79. #endif
  80. #define OPUS_ENCODER_RESET_START stream_channels
  81. int stream_channels;
  82. opus_int16 hybrid_stereo_width_Q14;
  83. opus_int32 variable_HP_smth2_Q15;
  84. opus_val16 prev_HB_gain;
  85. opus_val32 hp_mem[4];
  86. int mode;
  87. int prev_mode;
  88. int prev_channels;
  89. int prev_framesize;
  90. int bandwidth;
  91. int silk_bw_switch;
  92. /* Sampling rate (at the API level) */
  93. int first;
  94. opus_val16 * energy_masking;
  95. StereoWidthState width_mem;
  96. opus_val16 delay_buffer[MAX_ENCODER_BUFFER*2];
  97. #ifndef DISABLE_FLOAT_API
  98. int detected_bandwidth;
  99. #endif
  100. opus_uint32 rangeFinal;
  101. };
  102. /* Transition tables for the voice and music. First column is the
  103. middle (memoriless) threshold. The second column is the hysteresis
  104. (difference with the middle) */
  105. static const opus_int32 mono_voice_bandwidth_thresholds[8] = {
  106. 11000, 1000, /* NB<->MB */
  107. 14000, 1000, /* MB<->WB */
  108. 17000, 1000, /* WB<->SWB */
  109. 21000, 2000, /* SWB<->FB */
  110. };
  111. static const opus_int32 mono_music_bandwidth_thresholds[8] = {
  112. 12000, 1000, /* NB<->MB */
  113. 15000, 1000, /* MB<->WB */
  114. 18000, 2000, /* WB<->SWB */
  115. 22000, 2000, /* SWB<->FB */
  116. };
  117. static const opus_int32 stereo_voice_bandwidth_thresholds[8] = {
  118. 11000, 1000, /* NB<->MB */
  119. 14000, 1000, /* MB<->WB */
  120. 21000, 2000, /* WB<->SWB */
  121. 28000, 2000, /* SWB<->FB */
  122. };
  123. static const opus_int32 stereo_music_bandwidth_thresholds[8] = {
  124. 12000, 1000, /* NB<->MB */
  125. 18000, 2000, /* MB<->WB */
  126. 21000, 2000, /* WB<->SWB */
  127. 30000, 2000, /* SWB<->FB */
  128. };
  129. /* Threshold bit-rates for switching between mono and stereo */
  130. static const opus_int32 stereo_voice_threshold = 30000;
  131. static const opus_int32 stereo_music_threshold = 30000;
  132. /* Threshold bit-rate for switching between SILK/hybrid and CELT-only */
  133. static const opus_int32 mode_thresholds[2][2] = {
  134. /* voice */ /* music */
  135. { 64000, 16000}, /* mono */
  136. { 36000, 16000}, /* stereo */
  137. };
  138. int opus_encoder_get_size(int channels)
  139. {
  140. int silkEncSizeBytes, celtEncSizeBytes;
  141. int ret;
  142. if (channels<1 || channels > 2)
  143. return 0;
  144. ret = silk_Get_Encoder_Size( &silkEncSizeBytes );
  145. if (ret)
  146. return 0;
  147. silkEncSizeBytes = align(silkEncSizeBytes);
  148. celtEncSizeBytes = celt_encoder_get_size(channels);
  149. return align(sizeof(OpusEncoder))+silkEncSizeBytes+celtEncSizeBytes;
  150. }
  151. int opus_encoder_init(OpusEncoder* st, opus_int32 Fs, int channels, int application)
  152. {
  153. void *silk_enc;
  154. CELTEncoder *celt_enc;
  155. int err;
  156. int ret, silkEncSizeBytes;
  157. if((Fs!=48000&&Fs!=24000&&Fs!=16000&&Fs!=12000&&Fs!=8000)||(channels!=1&&channels!=2)||
  158. (application != OPUS_APPLICATION_VOIP && application != OPUS_APPLICATION_AUDIO
  159. && application != OPUS_APPLICATION_RESTRICTED_LOWDELAY))
  160. return OPUS_BAD_ARG;
  161. OPUS_CLEAR((char*)st, opus_encoder_get_size(channels));
  162. /* Create SILK encoder */
  163. ret = silk_Get_Encoder_Size( &silkEncSizeBytes );
  164. if (ret)
  165. return OPUS_BAD_ARG;
  166. silkEncSizeBytes = align(silkEncSizeBytes);
  167. st->silk_enc_offset = align(sizeof(OpusEncoder));
  168. st->celt_enc_offset = st->silk_enc_offset+silkEncSizeBytes;
  169. silk_enc = (char*)st+st->silk_enc_offset;
  170. celt_enc = (CELTEncoder*)((char*)st+st->celt_enc_offset);
  171. st->stream_channels = st->channels = channels;
  172. st->Fs = Fs;
  173. st->arch = opus_select_arch();
  174. ret = silk_InitEncoder( silk_enc, st->arch, &st->silk_mode );
  175. if(ret)return OPUS_INTERNAL_ERROR;
  176. /* default SILK parameters */
  177. st->silk_mode.nChannelsAPI = channels;
  178. st->silk_mode.nChannelsInternal = channels;
  179. st->silk_mode.API_sampleRate = st->Fs;
  180. st->silk_mode.maxInternalSampleRate = 16000;
  181. st->silk_mode.minInternalSampleRate = 8000;
  182. st->silk_mode.desiredInternalSampleRate = 16000;
  183. st->silk_mode.payloadSize_ms = 20;
  184. st->silk_mode.bitRate = 25000;
  185. st->silk_mode.packetLossPercentage = 0;
  186. st->silk_mode.complexity = 9;
  187. st->silk_mode.useInBandFEC = 0;
  188. st->silk_mode.useDTX = 0;
  189. st->silk_mode.useCBR = 0;
  190. st->silk_mode.reducedDependency = 0;
  191. /* Create CELT encoder */
  192. /* Initialize CELT encoder */
  193. err = celt_encoder_init(celt_enc, Fs, channels, st->arch);
  194. if(err!=OPUS_OK)return OPUS_INTERNAL_ERROR;
  195. celt_encoder_ctl(celt_enc, CELT_SET_SIGNALLING(0));
  196. celt_encoder_ctl(celt_enc, OPUS_SET_COMPLEXITY(st->silk_mode.complexity));
  197. st->use_vbr = 1;
  198. /* Makes constrained VBR the default (safer for real-time use) */
  199. st->vbr_constraint = 1;
  200. st->user_bitrate_bps = OPUS_AUTO;
  201. st->bitrate_bps = 3000+Fs*channels;
  202. st->application = application;
  203. st->signal_type = OPUS_AUTO;
  204. st->user_bandwidth = OPUS_AUTO;
  205. st->max_bandwidth = OPUS_BANDWIDTH_FULLBAND;
  206. st->force_channels = OPUS_AUTO;
  207. st->user_forced_mode = OPUS_AUTO;
  208. st->voice_ratio = -1;
  209. st->encoder_buffer = st->Fs/100;
  210. st->lsb_depth = 24;
  211. st->variable_duration = OPUS_FRAMESIZE_ARG;
  212. /* Delay compensation of 4 ms (2.5 ms for SILK's extra look-ahead
  213. + 1.5 ms for SILK resamplers and stereo prediction) */
  214. st->delay_compensation = st->Fs/250;
  215. st->hybrid_stereo_width_Q14 = 1 << 14;
  216. st->prev_HB_gain = Q15ONE;
  217. st->variable_HP_smth2_Q15 = silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 );
  218. st->first = 1;
  219. st->mode = MODE_HYBRID;
  220. st->bandwidth = OPUS_BANDWIDTH_FULLBAND;
  221. #ifndef DISABLE_FLOAT_API
  222. tonality_analysis_init(&st->analysis);
  223. #endif
  224. return OPUS_OK;
  225. }
  226. static unsigned char gen_toc(int mode, int framerate, int bandwidth, int channels)
  227. {
  228. int period;
  229. unsigned char toc;
  230. period = 0;
  231. while (framerate < 400)
  232. {
  233. framerate <<= 1;
  234. period++;
  235. }
  236. if (mode == MODE_SILK_ONLY)
  237. {
  238. toc = (bandwidth-OPUS_BANDWIDTH_NARROWBAND)<<5;
  239. toc |= (period-2)<<3;
  240. } else if (mode == MODE_CELT_ONLY)
  241. {
  242. int tmp = bandwidth-OPUS_BANDWIDTH_MEDIUMBAND;
  243. if (tmp < 0)
  244. tmp = 0;
  245. toc = 0x80;
  246. toc |= tmp << 5;
  247. toc |= period<<3;
  248. } else /* Hybrid */
  249. {
  250. toc = 0x60;
  251. toc |= (bandwidth-OPUS_BANDWIDTH_SUPERWIDEBAND)<<4;
  252. toc |= (period-2)<<3;
  253. }
  254. toc |= (channels==2)<<2;
  255. return toc;
  256. }
  257. #ifndef FIXED_POINT
  258. static void silk_biquad_float(
  259. const opus_val16 *in, /* I: Input signal */
  260. const opus_int32 *B_Q28, /* I: MA coefficients [3] */
  261. const opus_int32 *A_Q28, /* I: AR coefficients [2] */
  262. opus_val32 *S, /* I/O: State vector [2] */
  263. opus_val16 *out, /* O: Output signal */
  264. const opus_int32 len, /* I: Signal length (must be even) */
  265. int stride
  266. )
  267. {
  268. /* DIRECT FORM II TRANSPOSED (uses 2 element state vector) */
  269. opus_int k;
  270. opus_val32 vout;
  271. opus_val32 inval;
  272. opus_val32 A[2], B[3];
  273. A[0] = (opus_val32)(A_Q28[0] * (1.f/((opus_int32)1<<28)));
  274. A[1] = (opus_val32)(A_Q28[1] * (1.f/((opus_int32)1<<28)));
  275. B[0] = (opus_val32)(B_Q28[0] * (1.f/((opus_int32)1<<28)));
  276. B[1] = (opus_val32)(B_Q28[1] * (1.f/((opus_int32)1<<28)));
  277. B[2] = (opus_val32)(B_Q28[2] * (1.f/((opus_int32)1<<28)));
  278. /* Negate A_Q28 values and split in two parts */
  279. for( k = 0; k < len; k++ ) {
  280. /* S[ 0 ], S[ 1 ]: Q12 */
  281. inval = in[ k*stride ];
  282. vout = S[ 0 ] + B[0]*inval;
  283. S[ 0 ] = S[1] - vout*A[0] + B[1]*inval;
  284. S[ 1 ] = - vout*A[1] + B[2]*inval + VERY_SMALL;
  285. /* Scale back to Q0 and saturate */
  286. out[ k*stride ] = vout;
  287. }
  288. }
  289. #endif
  290. static void hp_cutoff(const opus_val16 *in, opus_int32 cutoff_Hz, opus_val16 *out, opus_val32 *hp_mem, int len, int channels, opus_int32 Fs)
  291. {
  292. opus_int32 B_Q28[ 3 ], A_Q28[ 2 ];
  293. opus_int32 Fc_Q19, r_Q28, r_Q22;
  294. silk_assert( cutoff_Hz <= silk_int32_MAX / SILK_FIX_CONST( 1.5 * 3.14159 / 1000, 19 ) );
  295. Fc_Q19 = silk_DIV32_16( silk_SMULBB( SILK_FIX_CONST( 1.5 * 3.14159 / 1000, 19 ), cutoff_Hz ), Fs/1000 );
  296. silk_assert( Fc_Q19 > 0 && Fc_Q19 < 32768 );
  297. r_Q28 = SILK_FIX_CONST( 1.0, 28 ) - silk_MUL( SILK_FIX_CONST( 0.92, 9 ), Fc_Q19 );
  298. /* b = r * [ 1; -2; 1 ]; */
  299. /* a = [ 1; -2 * r * ( 1 - 0.5 * Fc^2 ); r^2 ]; */
  300. B_Q28[ 0 ] = r_Q28;
  301. B_Q28[ 1 ] = silk_LSHIFT( -r_Q28, 1 );
  302. B_Q28[ 2 ] = r_Q28;
  303. /* -r * ( 2 - Fc * Fc ); */
  304. r_Q22 = silk_RSHIFT( r_Q28, 6 );
  305. A_Q28[ 0 ] = silk_SMULWW( r_Q22, silk_SMULWW( Fc_Q19, Fc_Q19 ) - SILK_FIX_CONST( 2.0, 22 ) );
  306. A_Q28[ 1 ] = silk_SMULWW( r_Q22, r_Q22 );
  307. #ifdef FIXED_POINT
  308. silk_biquad_alt( in, B_Q28, A_Q28, hp_mem, out, len, channels );
  309. if( channels == 2 ) {
  310. silk_biquad_alt( in+1, B_Q28, A_Q28, hp_mem+2, out+1, len, channels );
  311. }
  312. #else
  313. silk_biquad_float( in, B_Q28, A_Q28, hp_mem, out, len, channels );
  314. if( channels == 2 ) {
  315. silk_biquad_float( in+1, B_Q28, A_Q28, hp_mem+2, out+1, len, channels );
  316. }
  317. #endif
  318. }
  319. #ifdef FIXED_POINT
  320. static void dc_reject(const opus_val16 *in, opus_int32 cutoff_Hz, opus_val16 *out, opus_val32 *hp_mem, int len, int channels, opus_int32 Fs)
  321. {
  322. int c, i;
  323. int shift;
  324. /* Approximates -round(log2(4.*cutoff_Hz/Fs)) */
  325. shift=celt_ilog2(Fs/(cutoff_Hz*3));
  326. for (c=0;c<channels;c++)
  327. {
  328. for (i=0;i<len;i++)
  329. {
  330. opus_val32 x, tmp, y;
  331. x = SHL32(EXTEND32(in[channels*i+c]), 15);
  332. /* First stage */
  333. tmp = x-hp_mem[2*c];
  334. hp_mem[2*c] = hp_mem[2*c] + PSHR32(x - hp_mem[2*c], shift);
  335. /* Second stage */
  336. y = tmp - hp_mem[2*c+1];
  337. hp_mem[2*c+1] = hp_mem[2*c+1] + PSHR32(tmp - hp_mem[2*c+1], shift);
  338. out[channels*i+c] = EXTRACT16(SATURATE(PSHR32(y, 15), 32767));
  339. }
  340. }
  341. }
  342. #else
  343. static void dc_reject(const opus_val16 *in, opus_int32 cutoff_Hz, opus_val16 *out, opus_val32 *hp_mem, int len, int channels, opus_int32 Fs)
  344. {
  345. int c, i;
  346. float coef;
  347. coef = 4.0f*cutoff_Hz/Fs;
  348. for (c=0;c<channels;c++)
  349. {
  350. for (i=0;i<len;i++)
  351. {
  352. opus_val32 x, tmp, y;
  353. x = in[channels*i+c];
  354. /* First stage */
  355. tmp = x-hp_mem[2*c];
  356. hp_mem[2*c] = hp_mem[2*c] + coef*(x - hp_mem[2*c]) + VERY_SMALL;
  357. /* Second stage */
  358. y = tmp - hp_mem[2*c+1];
  359. hp_mem[2*c+1] = hp_mem[2*c+1] + coef*(tmp - hp_mem[2*c+1]) + VERY_SMALL;
  360. out[channels*i+c] = y;
  361. }
  362. }
  363. }
  364. #endif
  365. static void stereo_fade(const opus_val16 *in, opus_val16 *out, opus_val16 g1, opus_val16 g2,
  366. int overlap48, int frame_size, int channels, const opus_val16 *window, opus_int32 Fs)
  367. {
  368. int i;
  369. int overlap;
  370. int inc;
  371. inc = 48000/Fs;
  372. overlap=overlap48/inc;
  373. g1 = Q15ONE-g1;
  374. g2 = Q15ONE-g2;
  375. for (i=0;i<overlap;i++)
  376. {
  377. opus_val32 diff;
  378. opus_val16 g, w;
  379. w = MULT16_16_Q15(window[i*inc], window[i*inc]);
  380. g = SHR32(MAC16_16(MULT16_16(w,g2),
  381. Q15ONE-w, g1), 15);
  382. diff = EXTRACT16(HALF32((opus_val32)in[i*channels] - (opus_val32)in[i*channels+1]));
  383. diff = MULT16_16_Q15(g, diff);
  384. out[i*channels] = out[i*channels] - diff;
  385. out[i*channels+1] = out[i*channels+1] + diff;
  386. }
  387. for (;i<frame_size;i++)
  388. {
  389. opus_val32 diff;
  390. diff = EXTRACT16(HALF32((opus_val32)in[i*channels] - (opus_val32)in[i*channels+1]));
  391. diff = MULT16_16_Q15(g2, diff);
  392. out[i*channels] = out[i*channels] - diff;
  393. out[i*channels+1] = out[i*channels+1] + diff;
  394. }
  395. }
  396. static void gain_fade(const opus_val16 *in, opus_val16 *out, opus_val16 g1, opus_val16 g2,
  397. int overlap48, int frame_size, int channels, const opus_val16 *window, opus_int32 Fs)
  398. {
  399. int i;
  400. int inc;
  401. int overlap;
  402. int c;
  403. inc = 48000/Fs;
  404. overlap=overlap48/inc;
  405. if (channels==1)
  406. {
  407. for (i=0;i<overlap;i++)
  408. {
  409. opus_val16 g, w;
  410. w = MULT16_16_Q15(window[i*inc], window[i*inc]);
  411. g = SHR32(MAC16_16(MULT16_16(w,g2),
  412. Q15ONE-w, g1), 15);
  413. out[i] = MULT16_16_Q15(g, in[i]);
  414. }
  415. } else {
  416. for (i=0;i<overlap;i++)
  417. {
  418. opus_val16 g, w;
  419. w = MULT16_16_Q15(window[i*inc], window[i*inc]);
  420. g = SHR32(MAC16_16(MULT16_16(w,g2),
  421. Q15ONE-w, g1), 15);
  422. out[i*2] = MULT16_16_Q15(g, in[i*2]);
  423. out[i*2+1] = MULT16_16_Q15(g, in[i*2+1]);
  424. }
  425. }
  426. c=0;do {
  427. for (i=overlap;i<frame_size;i++)
  428. {
  429. out[i*channels+c] = MULT16_16_Q15(g2, in[i*channels+c]);
  430. }
  431. }
  432. while (++c<channels);
  433. }
  434. OpusEncoder *opus_encoder_create(opus_int32 Fs, int channels, int application, int *error)
  435. {
  436. int ret;
  437. OpusEncoder *st;
  438. if((Fs!=48000&&Fs!=24000&&Fs!=16000&&Fs!=12000&&Fs!=8000)||(channels!=1&&channels!=2)||
  439. (application != OPUS_APPLICATION_VOIP && application != OPUS_APPLICATION_AUDIO
  440. && application != OPUS_APPLICATION_RESTRICTED_LOWDELAY))
  441. {
  442. if (error)
  443. *error = OPUS_BAD_ARG;
  444. return NULL;
  445. }
  446. st = (OpusEncoder *)opus_alloc(opus_encoder_get_size(channels));
  447. if (st == NULL)
  448. {
  449. if (error)
  450. *error = OPUS_ALLOC_FAIL;
  451. return NULL;
  452. }
  453. ret = opus_encoder_init(st, Fs, channels, application);
  454. if (error)
  455. *error = ret;
  456. if (ret != OPUS_OK)
  457. {
  458. opus_free(st);
  459. st = NULL;
  460. }
  461. return st;
  462. }
  463. static opus_int32 user_bitrate_to_bitrate(OpusEncoder *st, int frame_size, int max_data_bytes)
  464. {
  465. if(!frame_size)frame_size=st->Fs/400;
  466. if (st->user_bitrate_bps==OPUS_AUTO)
  467. return 60*st->Fs/frame_size + st->Fs*st->channels;
  468. else if (st->user_bitrate_bps==OPUS_BITRATE_MAX)
  469. return max_data_bytes*8*st->Fs/frame_size;
  470. else
  471. return st->user_bitrate_bps;
  472. }
  473. #ifndef DISABLE_FLOAT_API
  474. /* Don't use more than 60 ms for the frame size analysis */
  475. #define MAX_DYNAMIC_FRAMESIZE 24
  476. /* Estimates how much the bitrate will be boosted based on the sub-frame energy */
  477. static float transient_boost(const float *E, const float *E_1, int LM, int maxM)
  478. {
  479. int i;
  480. int M;
  481. float sumE=0, sumE_1=0;
  482. float metric;
  483. M = IMIN(maxM, (1<<LM)+1);
  484. for (i=0;i<M;i++)
  485. {
  486. sumE += E[i];
  487. sumE_1 += E_1[i];
  488. }
  489. metric = sumE*sumE_1/(M*M);
  490. /*if (LM==3)
  491. printf("%f\n", metric);*/
  492. /*return metric>10 ? 1 : 0;*/
  493. /*return MAX16(0,1-exp(-.25*(metric-2.)));*/
  494. return MIN16(1,(float)sqrt(MAX16(0,.05f*(metric-2))));
  495. }
  496. /* Viterbi decoding trying to find the best frame size combination using look-ahead
  497. State numbering:
  498. 0: unused
  499. 1: 2.5 ms
  500. 2: 5 ms (#1)
  501. 3: 5 ms (#2)
  502. 4: 10 ms (#1)
  503. 5: 10 ms (#2)
  504. 6: 10 ms (#3)
  505. 7: 10 ms (#4)
  506. 8: 20 ms (#1)
  507. 9: 20 ms (#2)
  508. 10: 20 ms (#3)
  509. 11: 20 ms (#4)
  510. 12: 20 ms (#5)
  511. 13: 20 ms (#6)
  512. 14: 20 ms (#7)
  513. 15: 20 ms (#8)
  514. */
  515. static int transient_viterbi(const float *E, const float *E_1, int N, int frame_cost, int rate)
  516. {
  517. int i;
  518. float cost[MAX_DYNAMIC_FRAMESIZE][16];
  519. int states[MAX_DYNAMIC_FRAMESIZE][16];
  520. float best_cost;
  521. int best_state;
  522. float factor;
  523. /* Take into account that we damp VBR in the 32 kb/s to 64 kb/s range. */
  524. if (rate<80)
  525. factor=0;
  526. else if (rate>160)
  527. factor=1;
  528. else
  529. factor = (rate-80.f)/80.f;
  530. /* Makes variable framesize less aggressive at lower bitrates, but I can't
  531. find any valid theoretical justification for this (other than it seems
  532. to help) */
  533. for (i=0;i<16;i++)
  534. {
  535. /* Impossible state */
  536. states[0][i] = -1;
  537. cost[0][i] = 1e10;
  538. }
  539. for (i=0;i<4;i++)
  540. {
  541. cost[0][1<<i] = (frame_cost + rate*(1<<i))*(1+factor*transient_boost(E, E_1, i, N+1));
  542. states[0][1<<i] = i;
  543. }
  544. for (i=1;i<N;i++)
  545. {
  546. int j;
  547. /* Follow continuations */
  548. for (j=2;j<16;j++)
  549. {
  550. cost[i][j] = cost[i-1][j-1];
  551. states[i][j] = j-1;
  552. }
  553. /* New frames */
  554. for(j=0;j<4;j++)
  555. {
  556. int k;
  557. float min_cost;
  558. float curr_cost;
  559. states[i][1<<j] = 1;
  560. min_cost = cost[i-1][1];
  561. for(k=1;k<4;k++)
  562. {
  563. float tmp = cost[i-1][(1<<(k+1))-1];
  564. if (tmp < min_cost)
  565. {
  566. states[i][1<<j] = (1<<(k+1))-1;
  567. min_cost = tmp;
  568. }
  569. }
  570. curr_cost = (frame_cost + rate*(1<<j))*(1+factor*transient_boost(E+i, E_1+i, j, N-i+1));
  571. cost[i][1<<j] = min_cost;
  572. /* If part of the frame is outside the analysis window, only count part of the cost */
  573. if (N-i < (1<<j))
  574. cost[i][1<<j] += curr_cost*(float)(N-i)/(1<<j);
  575. else
  576. cost[i][1<<j] += curr_cost;
  577. }
  578. }
  579. best_state=1;
  580. best_cost = cost[N-1][1];
  581. /* Find best end state (doesn't force a frame to end at N-1) */
  582. for (i=2;i<16;i++)
  583. {
  584. if (cost[N-1][i]<best_cost)
  585. {
  586. best_cost = cost[N-1][i];
  587. best_state = i;
  588. }
  589. }
  590. /* Follow transitions back */
  591. for (i=N-1;i>=0;i--)
  592. {
  593. /*printf("%d ", best_state);*/
  594. best_state = states[i][best_state];
  595. }
  596. /*printf("%d\n", best_state);*/
  597. return best_state;
  598. }
  599. static int optimize_framesize(const void *x, int len, int C, opus_int32 Fs,
  600. int bitrate, opus_val16 tonality, float *mem, int buffering,
  601. downmix_func downmix)
  602. {
  603. int N;
  604. int i;
  605. float e[MAX_DYNAMIC_FRAMESIZE+4];
  606. float e_1[MAX_DYNAMIC_FRAMESIZE+3];
  607. opus_val32 memx;
  608. int bestLM=0;
  609. int subframe;
  610. int pos;
  611. int offset;
  612. VARDECL(opus_val32, sub);
  613. subframe = Fs/400;
  614. ALLOC(sub, subframe, opus_val32);
  615. e[0]=mem[0];
  616. e_1[0]=1.f/(EPSILON+mem[0]);
  617. if (buffering)
  618. {
  619. /* Consider the CELT delay when not in restricted-lowdelay */
  620. /* We assume the buffering is between 2.5 and 5 ms */
  621. offset = 2*subframe - buffering;
  622. celt_assert(offset>=0 && offset <= subframe);
  623. len -= offset;
  624. e[1]=mem[1];
  625. e_1[1]=1.f/(EPSILON+mem[1]);
  626. e[2]=mem[2];
  627. e_1[2]=1.f/(EPSILON+mem[2]);
  628. pos = 3;
  629. } else {
  630. pos=1;
  631. offset=0;
  632. }
  633. N=IMIN(len/subframe, MAX_DYNAMIC_FRAMESIZE);
  634. /* Just silencing a warning, it's really initialized later */
  635. memx = 0;
  636. for (i=0;i<N;i++)
  637. {
  638. float tmp;
  639. opus_val32 tmpx;
  640. int j;
  641. tmp=EPSILON;
  642. downmix(x, sub, subframe, i*subframe+offset, 0, -2, C);
  643. if (i==0)
  644. memx = sub[0];
  645. for (j=0;j<subframe;j++)
  646. {
  647. tmpx = sub[j];
  648. tmp += (tmpx-memx)*(float)(tmpx-memx);
  649. memx = tmpx;
  650. }
  651. e[i+pos] = tmp;
  652. e_1[i+pos] = 1.f/tmp;
  653. }
  654. /* Hack to get 20 ms working with APPLICATION_AUDIO
  655. The real problem is that the corresponding memory needs to use 1.5 ms
  656. from this frame and 1 ms from the next frame */
  657. e[i+pos] = e[i+pos-1];
  658. if (buffering)
  659. N=IMIN(MAX_DYNAMIC_FRAMESIZE, N+2);
  660. bestLM = transient_viterbi(e, e_1, N, (int)((1.f+.5f*tonality)*(60*C+40)), bitrate/400);
  661. mem[0] = e[1<<bestLM];
  662. if (buffering)
  663. {
  664. mem[1] = e[(1<<bestLM)+1];
  665. mem[2] = e[(1<<bestLM)+2];
  666. }
  667. return bestLM;
  668. }
  669. #endif
  670. #ifndef DISABLE_FLOAT_API
  671. #ifdef FIXED_POINT
  672. #define PCM2VAL(x) FLOAT2INT16(x)
  673. #else
  674. #define PCM2VAL(x) SCALEIN(x)
  675. #endif
  676. void downmix_float(const void *_x, opus_val32 *sub, int subframe, int offset, int c1, int c2, int C)
  677. {
  678. const float *x;
  679. opus_val32 scale;
  680. int j;
  681. x = (const float *)_x;
  682. for (j=0;j<subframe;j++)
  683. sub[j] = PCM2VAL(x[(j+offset)*C+c1]);
  684. if (c2>-1)
  685. {
  686. for (j=0;j<subframe;j++)
  687. sub[j] += PCM2VAL(x[(j+offset)*C+c2]);
  688. } else if (c2==-2)
  689. {
  690. int c;
  691. for (c=1;c<C;c++)
  692. {
  693. for (j=0;j<subframe;j++)
  694. sub[j] += PCM2VAL(x[(j+offset)*C+c]);
  695. }
  696. }
  697. #ifdef FIXED_POINT
  698. scale = (1<<SIG_SHIFT);
  699. #else
  700. scale = 1.f;
  701. #endif
  702. if (C==-2)
  703. scale /= C;
  704. else
  705. scale /= 2;
  706. for (j=0;j<subframe;j++)
  707. sub[j] *= scale;
  708. }
  709. #endif
  710. void downmix_int(const void *_x, opus_val32 *sub, int subframe, int offset, int c1, int c2, int C)
  711. {
  712. const opus_int16 *x;
  713. opus_val32 scale;
  714. int j;
  715. x = (const opus_int16 *)_x;
  716. for (j=0;j<subframe;j++)
  717. sub[j] = x[(j+offset)*C+c1];
  718. if (c2>-1)
  719. {
  720. for (j=0;j<subframe;j++)
  721. sub[j] += x[(j+offset)*C+c2];
  722. } else if (c2==-2)
  723. {
  724. int c;
  725. for (c=1;c<C;c++)
  726. {
  727. for (j=0;j<subframe;j++)
  728. sub[j] += x[(j+offset)*C+c];
  729. }
  730. }
  731. #ifdef FIXED_POINT
  732. scale = (1<<SIG_SHIFT);
  733. #else
  734. scale = 1.f/32768;
  735. #endif
  736. if (C==-2)
  737. scale /= C;
  738. else
  739. scale /= 2;
  740. for (j=0;j<subframe;j++)
  741. sub[j] *= scale;
  742. }
  743. opus_int32 frame_size_select(opus_int32 frame_size, int variable_duration, opus_int32 Fs)
  744. {
  745. int new_size;
  746. if (frame_size<Fs/400)
  747. return -1;
  748. if (variable_duration == OPUS_FRAMESIZE_ARG)
  749. new_size = frame_size;
  750. else if (variable_duration == OPUS_FRAMESIZE_VARIABLE)
  751. new_size = Fs/50;
  752. else if (variable_duration >= OPUS_FRAMESIZE_2_5_MS && variable_duration <= OPUS_FRAMESIZE_60_MS)
  753. new_size = IMIN(3*Fs/50, (Fs/400)<<(variable_duration-OPUS_FRAMESIZE_2_5_MS));
  754. else
  755. return -1;
  756. if (new_size>frame_size)
  757. return -1;
  758. if (400*new_size!=Fs && 200*new_size!=Fs && 100*new_size!=Fs &&
  759. 50*new_size!=Fs && 25*new_size!=Fs && 50*new_size!=3*Fs)
  760. return -1;
  761. return new_size;
  762. }
  763. opus_int32 compute_frame_size(const void *analysis_pcm, int frame_size,
  764. int variable_duration, int C, opus_int32 Fs, int bitrate_bps,
  765. int delay_compensation, downmix_func downmix
  766. #ifndef DISABLE_FLOAT_API
  767. , float *subframe_mem
  768. #endif
  769. )
  770. {
  771. #ifndef DISABLE_FLOAT_API
  772. if (variable_duration == OPUS_FRAMESIZE_VARIABLE && frame_size >= Fs/200)
  773. {
  774. int LM = 3;
  775. LM = optimize_framesize(analysis_pcm, frame_size, C, Fs, bitrate_bps,
  776. 0, subframe_mem, delay_compensation, downmix);
  777. while ((Fs/400<<LM)>frame_size)
  778. LM--;
  779. frame_size = (Fs/400<<LM);
  780. } else
  781. #else
  782. (void)analysis_pcm;
  783. (void)C;
  784. (void)bitrate_bps;
  785. (void)delay_compensation;
  786. (void)downmix;
  787. #endif
  788. {
  789. frame_size = frame_size_select(frame_size, variable_duration, Fs);
  790. }
  791. if (frame_size<0)
  792. return -1;
  793. return frame_size;
  794. }
  795. opus_val16 compute_stereo_width(const opus_val16 *pcm, int frame_size, opus_int32 Fs, StereoWidthState *mem)
  796. {
  797. opus_val32 xx, xy, yy;
  798. opus_val16 sqrt_xx, sqrt_yy;
  799. opus_val16 qrrt_xx, qrrt_yy;
  800. int frame_rate;
  801. int i;
  802. opus_val16 short_alpha;
  803. frame_rate = Fs/frame_size;
  804. short_alpha = Q15ONE - MULT16_16(25, Q15ONE)/IMAX(50,frame_rate);
  805. xx=xy=yy=0;
  806. /* Unroll by 4. The frame size is always a multiple of 4 *except* for
  807. 2.5 ms frames at 12 kHz. Since this setting is very rare (and very
  808. stupid), we just discard the last two samples. */
  809. for (i=0;i<frame_size-3;i+=4)
  810. {
  811. opus_val32 pxx=0;
  812. opus_val32 pxy=0;
  813. opus_val32 pyy=0;
  814. opus_val16 x, y;
  815. x = pcm[2*i];
  816. y = pcm[2*i+1];
  817. pxx = SHR32(MULT16_16(x,x),2);
  818. pxy = SHR32(MULT16_16(x,y),2);
  819. pyy = SHR32(MULT16_16(y,y),2);
  820. x = pcm[2*i+2];
  821. y = pcm[2*i+3];
  822. pxx += SHR32(MULT16_16(x,x),2);
  823. pxy += SHR32(MULT16_16(x,y),2);
  824. pyy += SHR32(MULT16_16(y,y),2);
  825. x = pcm[2*i+4];
  826. y = pcm[2*i+5];
  827. pxx += SHR32(MULT16_16(x,x),2);
  828. pxy += SHR32(MULT16_16(x,y),2);
  829. pyy += SHR32(MULT16_16(y,y),2);
  830. x = pcm[2*i+6];
  831. y = pcm[2*i+7];
  832. pxx += SHR32(MULT16_16(x,x),2);
  833. pxy += SHR32(MULT16_16(x,y),2);
  834. pyy += SHR32(MULT16_16(y,y),2);
  835. xx += SHR32(pxx, 10);
  836. xy += SHR32(pxy, 10);
  837. yy += SHR32(pyy, 10);
  838. }
  839. mem->XX += MULT16_32_Q15(short_alpha, xx-mem->XX);
  840. mem->XY += MULT16_32_Q15(short_alpha, xy-mem->XY);
  841. mem->YY += MULT16_32_Q15(short_alpha, yy-mem->YY);
  842. mem->XX = MAX32(0, mem->XX);
  843. mem->XY = MAX32(0, mem->XY);
  844. mem->YY = MAX32(0, mem->YY);
  845. if (MAX32(mem->XX, mem->YY)>QCONST16(8e-4f, 18))
  846. {
  847. opus_val16 corr;
  848. opus_val16 ldiff;
  849. opus_val16 width;
  850. sqrt_xx = celt_sqrt(mem->XX);
  851. sqrt_yy = celt_sqrt(mem->YY);
  852. qrrt_xx = celt_sqrt(sqrt_xx);
  853. qrrt_yy = celt_sqrt(sqrt_yy);
  854. /* Inter-channel correlation */
  855. mem->XY = MIN32(mem->XY, sqrt_xx*sqrt_yy);
  856. corr = SHR32(frac_div32(mem->XY,EPSILON+MULT16_16(sqrt_xx,sqrt_yy)),16);
  857. /* Approximate loudness difference */
  858. ldiff = MULT16_16(Q15ONE, ABS16(qrrt_xx-qrrt_yy))/(EPSILON+qrrt_xx+qrrt_yy);
  859. width = MULT16_16_Q15(celt_sqrt(QCONST32(1.f,30)-MULT16_16(corr,corr)), ldiff);
  860. /* Smoothing over one second */
  861. mem->smoothed_width += (width-mem->smoothed_width)/frame_rate;
  862. /* Peak follower */
  863. mem->max_follower = MAX16(mem->max_follower-QCONST16(.02f,15)/frame_rate, mem->smoothed_width);
  864. }
  865. /*printf("%f %f %f %f %f ", corr/(float)Q15ONE, ldiff/(float)Q15ONE, width/(float)Q15ONE, mem->smoothed_width/(float)Q15ONE, mem->max_follower/(float)Q15ONE);*/
  866. return EXTRACT16(MIN32(Q15ONE, MULT16_16(20, mem->max_follower)));
  867. }
  868. opus_int32 opus_encode_native(OpusEncoder *st, const opus_val16 *pcm, int frame_size,
  869. unsigned char *data, opus_int32 out_data_bytes, int lsb_depth,
  870. const void *analysis_pcm, opus_int32 analysis_size, int c1, int c2,
  871. int analysis_channels, downmix_func downmix, int float_api)
  872. {
  873. void *silk_enc;
  874. CELTEncoder *celt_enc;
  875. int i;
  876. int ret=0;
  877. opus_int32 nBytes;
  878. ec_enc enc;
  879. int bytes_target;
  880. int prefill=0;
  881. int start_band = 0;
  882. int redundancy = 0;
  883. int redundancy_bytes = 0; /* Number of bytes to use for redundancy frame */
  884. int celt_to_silk = 0;
  885. VARDECL(opus_val16, pcm_buf);
  886. int nb_compr_bytes;
  887. int to_celt = 0;
  888. opus_uint32 redundant_rng = 0;
  889. int cutoff_Hz, hp_freq_smth1;
  890. int voice_est; /* Probability of voice in Q7 */
  891. opus_int32 equiv_rate;
  892. int delay_compensation;
  893. int frame_rate;
  894. opus_int32 max_rate; /* Max bitrate we're allowed to use */
  895. int curr_bandwidth;
  896. opus_val16 HB_gain;
  897. opus_int32 max_data_bytes; /* Max number of bytes we're allowed to use */
  898. int total_buffer;
  899. opus_val16 stereo_width;
  900. const CELTMode *celt_mode;
  901. #ifndef DISABLE_FLOAT_API
  902. AnalysisInfo analysis_info;
  903. int analysis_read_pos_bak=-1;
  904. int analysis_read_subframe_bak=-1;
  905. #endif
  906. VARDECL(opus_val16, tmp_prefill);
  907. ALLOC_STACK;
  908. max_data_bytes = IMIN(1276, out_data_bytes);
  909. st->rangeFinal = 0;
  910. if ((!st->variable_duration && 400*frame_size != st->Fs && 200*frame_size != st->Fs && 100*frame_size != st->Fs &&
  911. 50*frame_size != st->Fs && 25*frame_size != st->Fs && 50*frame_size != 3*st->Fs)
  912. || (400*frame_size < st->Fs)
  913. || max_data_bytes<=0
  914. )
  915. {
  916. RESTORE_STACK;
  917. return OPUS_BAD_ARG;
  918. }
  919. silk_enc = (char*)st+st->silk_enc_offset;
  920. celt_enc = (CELTEncoder*)((char*)st+st->celt_enc_offset);
  921. if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
  922. delay_compensation = 0;
  923. else
  924. delay_compensation = st->delay_compensation;
  925. lsb_depth = IMIN(lsb_depth, st->lsb_depth);
  926. celt_encoder_ctl(celt_enc, CELT_GET_MODE(&celt_mode));
  927. #ifndef DISABLE_FLOAT_API
  928. analysis_info.valid = 0;
  929. #ifdef FIXED_POINT
  930. if (st->silk_mode.complexity >= 10 && st->Fs==48000)
  931. #else
  932. if (st->silk_mode.complexity >= 7 && st->Fs==48000)
  933. #endif
  934. {
  935. analysis_read_pos_bak = st->analysis.read_pos;
  936. analysis_read_subframe_bak = st->analysis.read_subframe;
  937. run_analysis(&st->analysis, celt_mode, analysis_pcm, analysis_size, frame_size,
  938. c1, c2, analysis_channels, st->Fs,
  939. lsb_depth, downmix, &analysis_info);
  940. }
  941. #else
  942. (void)analysis_pcm;
  943. (void)analysis_size;
  944. #endif
  945. st->voice_ratio = -1;
  946. #ifndef DISABLE_FLOAT_API
  947. st->detected_bandwidth = 0;
  948. if (analysis_info.valid)
  949. {
  950. int analysis_bandwidth;
  951. if (st->signal_type == OPUS_AUTO)
  952. st->voice_ratio = (int)floor(.5+100*(1-analysis_info.music_prob));
  953. analysis_bandwidth = analysis_info.bandwidth;
  954. if (analysis_bandwidth<=12)
  955. st->detected_bandwidth = OPUS_BANDWIDTH_NARROWBAND;
  956. else if (analysis_bandwidth<=14)
  957. st->detected_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
  958. else if (analysis_bandwidth<=16)
  959. st->detected_bandwidth = OPUS_BANDWIDTH_WIDEBAND;
  960. else if (analysis_bandwidth<=18)
  961. st->detected_bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
  962. else
  963. st->detected_bandwidth = OPUS_BANDWIDTH_FULLBAND;
  964. }
  965. #endif
  966. if (st->channels==2 && st->force_channels!=1)
  967. stereo_width = compute_stereo_width(pcm, frame_size, st->Fs, &st->width_mem);
  968. else
  969. stereo_width = 0;
  970. total_buffer = delay_compensation;
  971. st->bitrate_bps = user_bitrate_to_bitrate(st, frame_size, max_data_bytes);
  972. frame_rate = st->Fs/frame_size;
  973. if (!st->use_vbr)
  974. {
  975. int cbrBytes;
  976. /* Multiply by 3 to make sure the division is exact. */
  977. int frame_rate3 = 3*st->Fs/frame_size;
  978. /* We need to make sure that "int" values always fit in 16 bits. */
  979. cbrBytes = IMIN( (3*st->bitrate_bps/8 + frame_rate3/2)/frame_rate3, max_data_bytes);
  980. st->bitrate_bps = cbrBytes*(opus_int32)frame_rate3*8/3;
  981. max_data_bytes = cbrBytes;
  982. }
  983. if (max_data_bytes<3 || st->bitrate_bps < 3*frame_rate*8
  984. || (frame_rate<50 && (max_data_bytes*frame_rate<300 || st->bitrate_bps < 2400)))
  985. {
  986. /*If the space is too low to do something useful, emit 'PLC' frames.*/
  987. int tocmode = st->mode;
  988. int bw = st->bandwidth == 0 ? OPUS_BANDWIDTH_NARROWBAND : st->bandwidth;
  989. if (tocmode==0)
  990. tocmode = MODE_SILK_ONLY;
  991. if (frame_rate>100)
  992. tocmode = MODE_CELT_ONLY;
  993. if (frame_rate < 50)
  994. tocmode = MODE_SILK_ONLY;
  995. if(tocmode==MODE_SILK_ONLY&&bw>OPUS_BANDWIDTH_WIDEBAND)
  996. bw=OPUS_BANDWIDTH_WIDEBAND;
  997. else if (tocmode==MODE_CELT_ONLY&&bw==OPUS_BANDWIDTH_MEDIUMBAND)
  998. bw=OPUS_BANDWIDTH_NARROWBAND;
  999. else if (tocmode==MODE_HYBRID&&bw<=OPUS_BANDWIDTH_SUPERWIDEBAND)
  1000. bw=OPUS_BANDWIDTH_SUPERWIDEBAND;
  1001. data[0] = gen_toc(tocmode, frame_rate, bw, st->stream_channels);
  1002. ret = 1;
  1003. if (!st->use_vbr)
  1004. {
  1005. ret = opus_packet_pad(data, ret, max_data_bytes);
  1006. if (ret == OPUS_OK)
  1007. ret = max_data_bytes;
  1008. }
  1009. RESTORE_STACK;
  1010. return ret;
  1011. }
  1012. max_rate = frame_rate*max_data_bytes*8;
  1013. /* Equivalent 20-ms rate for mode/channel/bandwidth decisions */
  1014. equiv_rate = st->bitrate_bps - (40*st->channels+20)*(st->Fs/frame_size - 50);
  1015. if (st->signal_type == OPUS_SIGNAL_VOICE)
  1016. voice_est = 127;
  1017. else if (st->signal_type == OPUS_SIGNAL_MUSIC)
  1018. voice_est = 0;
  1019. else if (st->voice_ratio >= 0)
  1020. {
  1021. voice_est = st->voice_ratio*327>>8;
  1022. /* For AUDIO, never be more than 90% confident of having speech */
  1023. if (st->application == OPUS_APPLICATION_AUDIO)
  1024. voice_est = IMIN(voice_est, 115);
  1025. } else if (st->application == OPUS_APPLICATION_VOIP)
  1026. voice_est = 115;
  1027. else
  1028. voice_est = 48;
  1029. if (st->force_channels!=OPUS_AUTO && st->channels == 2)
  1030. {
  1031. st->stream_channels = st->force_channels;
  1032. } else {
  1033. #ifdef FUZZING
  1034. /* Random mono/stereo decision */
  1035. if (st->channels == 2 && (rand()&0x1F)==0)
  1036. st->stream_channels = 3-st->stream_channels;
  1037. #else
  1038. /* Rate-dependent mono-stereo decision */
  1039. if (st->channels == 2)
  1040. {
  1041. opus_int32 stereo_threshold;
  1042. stereo_threshold = stereo_music_threshold + ((voice_est*voice_est*(stereo_voice_threshold-stereo_music_threshold))>>14);
  1043. if (st->stream_channels == 2)
  1044. stereo_threshold -= 1000;
  1045. else
  1046. stereo_threshold += 1000;
  1047. st->stream_channels = (equiv_rate > stereo_threshold) ? 2 : 1;
  1048. } else {
  1049. st->stream_channels = st->channels;
  1050. }
  1051. #endif
  1052. }
  1053. equiv_rate = st->bitrate_bps - (40*st->stream_channels+20)*(st->Fs/frame_size - 50);
  1054. /* Mode selection depending on application and signal type */
  1055. if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
  1056. {
  1057. st->mode = MODE_CELT_ONLY;
  1058. } else if (st->user_forced_mode == OPUS_AUTO)
  1059. {
  1060. #ifdef FUZZING
  1061. /* Random mode switching */
  1062. if ((rand()&0xF)==0)
  1063. {
  1064. if ((rand()&0x1)==0)
  1065. st->mode = MODE_CELT_ONLY;
  1066. else
  1067. st->mode = MODE_SILK_ONLY;
  1068. } else {
  1069. if (st->prev_mode==MODE_CELT_ONLY)
  1070. st->mode = MODE_CELT_ONLY;
  1071. else
  1072. st->mode = MODE_SILK_ONLY;
  1073. }
  1074. #else
  1075. opus_int32 mode_voice, mode_music;
  1076. opus_int32 threshold;
  1077. /* Interpolate based on stereo width */
  1078. mode_voice = (opus_int32)(MULT16_32_Q15(Q15ONE-stereo_width,mode_thresholds[0][0])
  1079. + MULT16_32_Q15(stereo_width,mode_thresholds[1][0]));
  1080. mode_music = (opus_int32)(MULT16_32_Q15(Q15ONE-stereo_width,mode_thresholds[1][1])
  1081. + MULT16_32_Q15(stereo_width,mode_thresholds[1][1]));
  1082. /* Interpolate based on speech/music probability */
  1083. threshold = mode_music + ((voice_est*voice_est*(mode_voice-mode_music))>>14);
  1084. /* Bias towards SILK for VoIP because of some useful features */
  1085. if (st->application == OPUS_APPLICATION_VOIP)
  1086. threshold += 8000;
  1087. /*printf("%f %d\n", stereo_width/(float)Q15ONE, threshold);*/
  1088. /* Hysteresis */
  1089. if (st->prev_mode == MODE_CELT_ONLY)
  1090. threshold -= 4000;
  1091. else if (st->prev_mode>0)
  1092. threshold += 4000;
  1093. st->mode = (equiv_rate >= threshold) ? MODE_CELT_ONLY: MODE_SILK_ONLY;
  1094. /* When FEC is enabled and there's enough packet loss, use SILK */
  1095. if (st->silk_mode.useInBandFEC && st->silk_mode.packetLossPercentage > (128-voice_est)>>4)
  1096. st->mode = MODE_SILK_ONLY;
  1097. /* When encoding voice and DTX is enabled, set the encoder to SILK mode (at least for now) */
  1098. if (st->silk_mode.useDTX && voice_est > 100)
  1099. st->mode = MODE_SILK_ONLY;
  1100. #endif
  1101. } else {
  1102. st->mode = st->user_forced_mode;
  1103. }
  1104. /* Override the chosen mode to make sure we meet the requested frame size */
  1105. if (st->mode != MODE_CELT_ONLY && frame_size < st->Fs/100)
  1106. st->mode = MODE_CELT_ONLY;
  1107. if (st->lfe)
  1108. st->mode = MODE_CELT_ONLY;
  1109. /* If max_data_bytes represents less than 8 kb/s, switch to CELT-only mode */
  1110. if (max_data_bytes < (frame_rate > 50 ? 12000 : 8000)*frame_size / (st->Fs * 8))
  1111. st->mode = MODE_CELT_ONLY;
  1112. if (st->stream_channels == 1 && st->prev_channels ==2 && st->silk_mode.toMono==0
  1113. && st->mode != MODE_CELT_ONLY && st->prev_mode != MODE_CELT_ONLY)
  1114. {
  1115. /* Delay stereo->mono transition by two frames so that SILK can do a smooth downmix */
  1116. st->silk_mode.toMono = 1;
  1117. st->stream_channels = 2;
  1118. } else {
  1119. st->silk_mode.toMono = 0;
  1120. }
  1121. if (st->prev_mode > 0 &&
  1122. ((st->mode != MODE_CELT_ONLY && st->prev_mode == MODE_CELT_ONLY) ||
  1123. (st->mode == MODE_CELT_ONLY && st->prev_mode != MODE_CELT_ONLY)))
  1124. {
  1125. redundancy = 1;
  1126. celt_to_silk = (st->mode != MODE_CELT_ONLY);
  1127. if (!celt_to_silk)
  1128. {
  1129. /* Switch to SILK/hybrid if frame size is 10 ms or more*/
  1130. if (frame_size >= st->Fs/100)
  1131. {
  1132. st->mode = st->prev_mode;
  1133. to_celt = 1;
  1134. } else {
  1135. redundancy=0;
  1136. }
  1137. }
  1138. }
  1139. /* For the first frame at a new SILK bandwidth */
  1140. if (st->silk_bw_switch)
  1141. {
  1142. redundancy = 1;
  1143. celt_to_silk = 1;
  1144. st->silk_bw_switch = 0;
  1145. prefill=1;
  1146. }
  1147. if (redundancy)
  1148. {
  1149. /* Fair share of the max size allowed */
  1150. redundancy_bytes = IMIN(257, max_data_bytes*(opus_int32)(st->Fs/200)/(frame_size+st->Fs/200));
  1151. /* For VBR, target the actual bitrate (subject to the limit above) */
  1152. if (st->use_vbr)
  1153. redundancy_bytes = IMIN(redundancy_bytes, st->bitrate_bps/1600);
  1154. }
  1155. if (st->mode != MODE_CELT_ONLY && st->prev_mode == MODE_CELT_ONLY)
  1156. {
  1157. silk_EncControlStruct dummy;
  1158. silk_InitEncoder( silk_enc, st->arch, &dummy);
  1159. prefill=1;
  1160. }
  1161. /* Automatic (rate-dependent) bandwidth selection */
  1162. if (st->mode == MODE_CELT_ONLY || st->first || st->silk_mode.allowBandwidthSwitch)
  1163. {
  1164. const opus_int32 *voice_bandwidth_thresholds, *music_bandwidth_thresholds;
  1165. opus_int32 bandwidth_thresholds[8];
  1166. int bandwidth = OPUS_BANDWIDTH_FULLBAND;
  1167. opus_int32 equiv_rate2;
  1168. equiv_rate2 = equiv_rate;
  1169. if (st->mode != MODE_CELT_ONLY)
  1170. {
  1171. /* Adjust the threshold +/- 10% depending on complexity */
  1172. equiv_rate2 = equiv_rate2 * (45+st->silk_mode.complexity)/50;
  1173. /* CBR is less efficient by ~1 kb/s */
  1174. if (!st->use_vbr)
  1175. equiv_rate2 -= 1000;
  1176. }
  1177. if (st->channels==2 && st->force_channels!=1)
  1178. {
  1179. voice_bandwidth_thresholds = stereo_voice_bandwidth_thresholds;
  1180. music_bandwidth_thresholds = stereo_music_bandwidth_thresholds;
  1181. } else {
  1182. voice_bandwidth_thresholds = mono_voice_bandwidth_thresholds;
  1183. music_bandwidth_thresholds = mono_music_bandwidth_thresholds;
  1184. }
  1185. /* Interpolate bandwidth thresholds depending on voice estimation */
  1186. for (i=0;i<8;i++)
  1187. {
  1188. bandwidth_thresholds[i] = music_bandwidth_thresholds[i]
  1189. + ((voice_est*voice_est*(voice_bandwidth_thresholds[i]-music_bandwidth_thresholds[i]))>>14);
  1190. }
  1191. do {
  1192. int threshold, hysteresis;
  1193. threshold = bandwidth_thresholds[2*(bandwidth-OPUS_BANDWIDTH_MEDIUMBAND)];
  1194. hysteresis = bandwidth_thresholds[2*(bandwidth-OPUS_BANDWIDTH_MEDIUMBAND)+1];
  1195. if (!st->first)
  1196. {
  1197. if (st->bandwidth >= bandwidth)
  1198. threshold -= hysteresis;
  1199. else
  1200. threshold += hysteresis;
  1201. }
  1202. if (equiv_rate2 >= threshold)
  1203. break;
  1204. } while (--bandwidth>OPUS_BANDWIDTH_NARROWBAND);
  1205. st->bandwidth = bandwidth;
  1206. /* Prevents any transition to SWB/FB until the SILK layer has fully
  1207. switched to WB mode and turned the variable LP filter off */
  1208. if (!st->first && st->mode != MODE_CELT_ONLY && !st->silk_mode.inWBmodeWithoutVariableLP && st->bandwidth > OPUS_BANDWIDTH_WIDEBAND)
  1209. st->bandwidth = OPUS_BANDWIDTH_WIDEBAND;
  1210. }
  1211. if (st->bandwidth>st->max_bandwidth)
  1212. st->bandwidth = st->max_bandwidth;
  1213. if (st->user_bandwidth != OPUS_AUTO)
  1214. st->bandwidth = st->user_bandwidth;
  1215. /* This prevents us from using hybrid at unsafe CBR/max rates */
  1216. if (st->mode != MODE_CELT_ONLY && max_rate < 15000)
  1217. {
  1218. st->bandwidth = IMIN(st->bandwidth, OPUS_BANDWIDTH_WIDEBAND);
  1219. }
  1220. /* Prevents Opus from wasting bits on frequencies that are above
  1221. the Nyquist rate of the input signal */
  1222. if (st->Fs <= 24000 && st->bandwidth > OPUS_BANDWIDTH_SUPERWIDEBAND)
  1223. st->bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
  1224. if (st->Fs <= 16000 && st->bandwidth > OPUS_BANDWIDTH_WIDEBAND)
  1225. st->bandwidth = OPUS_BANDWIDTH_WIDEBAND;
  1226. if (st->Fs <= 12000 && st->bandwidth > OPUS_BANDWIDTH_MEDIUMBAND)
  1227. st->bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
  1228. if (st->Fs <= 8000 && st->bandwidth > OPUS_BANDWIDTH_NARROWBAND)
  1229. st->bandwidth = OPUS_BANDWIDTH_NARROWBAND;
  1230. #ifndef DISABLE_FLOAT_API
  1231. /* Use detected bandwidth to reduce the encoded bandwidth. */
  1232. if (st->detected_bandwidth && st->user_bandwidth == OPUS_AUTO)
  1233. {
  1234. int min_detected_bandwidth;
  1235. /* Makes bandwidth detection more conservative just in case the detector
  1236. gets it wrong when we could have coded a high bandwidth transparently.
  1237. When operating in SILK/hybrid mode, we don't go below wideband to avoid
  1238. more complicated switches that require redundancy. */
  1239. if (equiv_rate <= 18000*st->stream_channels && st->mode == MODE_CELT_ONLY)
  1240. min_detected_bandwidth = OPUS_BANDWIDTH_NARROWBAND;
  1241. else if (equiv_rate <= 24000*st->stream_channels && st->mode == MODE_CELT_ONLY)
  1242. min_detected_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
  1243. else if (equiv_rate <= 30000*st->stream_channels)
  1244. min_detected_bandwidth = OPUS_BANDWIDTH_WIDEBAND;
  1245. else if (equiv_rate <= 44000*st->stream_channels)
  1246. min_detected_bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
  1247. else
  1248. min_detected_bandwidth = OPUS_BANDWIDTH_FULLBAND;
  1249. st->detected_bandwidth = IMAX(st->detected_bandwidth, min_detected_bandwidth);
  1250. st->bandwidth = IMIN(st->bandwidth, st->detected_bandwidth);
  1251. }
  1252. #endif
  1253. celt_encoder_ctl(celt_enc, OPUS_SET_LSB_DEPTH(lsb_depth));
  1254. /* CELT mode doesn't support mediumband, use wideband instead */
  1255. if (st->mode == MODE_CELT_ONLY && st->bandwidth == OPUS_BANDWIDTH_MEDIUMBAND)
  1256. st->bandwidth = OPUS_BANDWIDTH_WIDEBAND;
  1257. if (st->lfe)
  1258. st->bandwidth = OPUS_BANDWIDTH_NARROWBAND;
  1259. /* Can't support higher than wideband for >20 ms frames */
  1260. if (frame_size > st->Fs/50 && (st->mode == MODE_CELT_ONLY || st->bandwidth > OPUS_BANDWIDTH_WIDEBAND))
  1261. {
  1262. VARDECL(unsigned char, tmp_data);
  1263. int nb_frames;
  1264. int bak_mode, bak_bandwidth, bak_channels, bak_to_mono;
  1265. VARDECL(OpusRepacketizer, rp);
  1266. opus_int32 bytes_per_frame;
  1267. opus_int32 repacketize_len;
  1268. #ifndef DISABLE_FLOAT_API
  1269. if (analysis_read_pos_bak!= -1)
  1270. {
  1271. st->analysis.read_pos = analysis_read_pos_bak;
  1272. st->analysis.read_subframe = analysis_read_subframe_bak;
  1273. }
  1274. #endif
  1275. nb_frames = frame_size > st->Fs/25 ? 3 : 2;
  1276. bytes_per_frame = IMIN(1276,(out_data_bytes-3)/nb_frames);
  1277. ALLOC(tmp_data, nb_frames*bytes_per_frame, unsigned char);
  1278. ALLOC(rp, 1, OpusRepacketizer);
  1279. opus_repacketizer_init(rp);
  1280. bak_mode = st->user_forced_mode;
  1281. bak_bandwidth = st->user_bandwidth;
  1282. bak_channels = st->force_channels;
  1283. st->user_forced_mode = st->mode;
  1284. st->user_bandwidth = st->bandwidth;
  1285. st->force_channels = st->stream_channels;
  1286. bak_to_mono = st->silk_mode.toMono;
  1287. if (bak_to_mono)
  1288. st->force_channels = 1;
  1289. else
  1290. st->prev_channels = st->stream_channels;
  1291. for (i=0;i<nb_frames;i++)
  1292. {
  1293. int tmp_len;
  1294. st->silk_mode.toMono = 0;
  1295. /* When switching from SILK/Hybrid to CELT, only ask for a switch at the last frame */
  1296. if (to_celt && i==nb_frames-1)
  1297. st->user_forced_mode = MODE_CELT_ONLY;
  1298. tmp_len = opus_encode_native(st, pcm+i*(st->channels*st->Fs/50), st->Fs/50,
  1299. tmp_data+i*bytes_per_frame, bytes_per_frame, lsb_depth,
  1300. NULL, 0, c1, c2, analysis_channels, downmix, float_api);
  1301. if (tmp_len<0)
  1302. {
  1303. RESTORE_STACK;
  1304. return OPUS_INTERNAL_ERROR;
  1305. }
  1306. ret = opus_repacketizer_cat(rp, tmp_data+i*bytes_per_frame, tmp_len);
  1307. if (ret<0)
  1308. {
  1309. RESTORE_STACK;
  1310. return OPUS_INTERNAL_ERROR;
  1311. }
  1312. }
  1313. if (st->use_vbr)
  1314. repacketize_len = out_data_bytes;
  1315. else
  1316. repacketize_len = IMIN(3*st->bitrate_bps/(3*8*50/nb_frames), out_data_bytes);
  1317. ret = opus_repacketizer_out_range_impl(rp, 0, nb_frames, data, repacketize_len, 0, !st->use_vbr);
  1318. if (ret<0)
  1319. {
  1320. RESTORE_STACK;
  1321. return OPUS_INTERNAL_ERROR;
  1322. }
  1323. st->user_forced_mode = bak_mode;
  1324. st->user_bandwidth = bak_bandwidth;
  1325. st->force_channels = bak_channels;
  1326. st->silk_mode.toMono = bak_to_mono;
  1327. RESTORE_STACK;
  1328. return ret;
  1329. }
  1330. curr_bandwidth = st->bandwidth;
  1331. /* Chooses the appropriate mode for speech
  1332. *NEVER* switch to/from CELT-only mode here as this will invalidate some assumptions */
  1333. if (st->mode == MODE_SILK_ONLY && curr_bandwidth > OPUS_BANDWIDTH_WIDEBAND)
  1334. st->mode = MODE_HYBRID;
  1335. if (st->mode == MODE_HYBRID && curr_bandwidth <= OPUS_BANDWIDTH_WIDEBAND)
  1336. st->mode = MODE_SILK_ONLY;
  1337. /* printf("%d %d %d %d\n", st->bitrate_bps, st->stream_channels, st->mode, curr_bandwidth); */
  1338. bytes_target = IMIN(max_data_bytes-redundancy_bytes, st->bitrate_bps * frame_size / (st->Fs * 8)) - 1;
  1339. data += 1;
  1340. ec_enc_init(&enc, data, max_data_bytes-1);
  1341. ALLOC(pcm_buf, (total_buffer+frame_size)*st->channels, opus_val16);
  1342. OPUS_COPY(pcm_buf, &st->delay_buffer[(st->encoder_buffer-total_buffer)*st->channels], total_buffer*st->channels);
  1343. if (st->mode == MODE_CELT_ONLY)
  1344. hp_freq_smth1 = silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 );
  1345. else
  1346. hp_freq_smth1 = ((silk_encoder*)silk_enc)->state_Fxx[0].sCmn.variable_HP_smth1_Q15;
  1347. st->variable_HP_smth2_Q15 = silk_SMLAWB( st->variable_HP_smth2_Q15,
  1348. hp_freq_smth1 - st->variable_HP_smth2_Q15, SILK_FIX_CONST( VARIABLE_HP_SMTH_COEF2, 16 ) );
  1349. /* convert from log scale to Hertz */
  1350. cutoff_Hz = silk_log2lin( silk_RSHIFT( st->variable_HP_smth2_Q15, 8 ) );
  1351. if (st->application == OPUS_APPLICATION_VOIP)
  1352. {
  1353. hp_cutoff(pcm, cutoff_Hz, &pcm_buf[total_buffer*st->channels], st->hp_mem, frame_size, st->channels, st->Fs);
  1354. } else {
  1355. dc_reject(pcm, 3, &pcm_buf[total_buffer*st->channels], st->hp_mem, frame_size, st->channels, st->Fs);
  1356. }
  1357. #ifndef FIXED_POINT
  1358. if (float_api)
  1359. {
  1360. opus_val32 sum;
  1361. sum = celt_inner_prod(&pcm_buf[total_buffer*st->channels], &pcm_buf[total_buffer*st->channels], frame_size*st->channels, st->arch);
  1362. /* This should filter out both NaNs and ridiculous signals that could
  1363. cause NaNs further down. */
  1364. if (!(sum < 1e9f) || celt_isnan(sum))
  1365. {
  1366. OPUS_CLEAR(&pcm_buf[total_buffer*st->channels], frame_size*st->channels);
  1367. st->hp_mem[0] = st->hp_mem[1] = st->hp_mem[2] = st->hp_mem[3] = 0;
  1368. }
  1369. }
  1370. #endif
  1371. /* SILK processing */
  1372. HB_gain = Q15ONE;
  1373. if (st->mode != MODE_CELT_ONLY)
  1374. {
  1375. opus_int32 total_bitRate, celt_rate;
  1376. #ifdef FIXED_POINT
  1377. const opus_int16 *pcm_silk;
  1378. #else
  1379. VARDECL(opus_int16, pcm_silk);
  1380. ALLOC(pcm_silk, st->channels*frame_size, opus_int16);
  1381. #endif
  1382. /* Distribute bits between SILK and CELT */
  1383. total_bitRate = 8 * bytes_target * frame_rate;
  1384. if( st->mode == MODE_HYBRID ) {
  1385. int HB_gain_ref;
  1386. /* Base rate for SILK */
  1387. st->silk_mode.bitRate = st->stream_channels * ( 5000 + 1000 * ( st->Fs == 100 * frame_size ) );
  1388. if( curr_bandwidth == OPUS_BANDWIDTH_SUPERWIDEBAND ) {
  1389. /* SILK gets 2/3 of the remaining bits */
  1390. st->silk_mode.bitRate += ( total_bitRate - st->silk_mode.bitRate ) * 2 / 3;
  1391. } else { /* FULLBAND */
  1392. /* SILK gets 3/5 of the remaining bits */
  1393. st->silk_mode.bitRate += ( total_bitRate - st->silk_mode.bitRate ) * 3 / 5;
  1394. }
  1395. /* Don't let SILK use more than 80% */
  1396. if( st->silk_mode.bitRate > total_bitRate * 4/5 ) {
  1397. st->silk_mode.bitRate = total_bitRate * 4/5;
  1398. }
  1399. if (!st->energy_masking)
  1400. {
  1401. /* Increasingly attenuate high band when it gets allocated fewer bits */
  1402. celt_rate = total_bitRate - st->silk_mode.bitRate;
  1403. HB_gain_ref = (curr_bandwidth == OPUS_BANDWIDTH_SUPERWIDEBAND) ? 3000 : 3600;
  1404. HB_gain = SHL32((opus_val32)celt_rate, 9) / SHR32((opus_val32)celt_rate + st->stream_channels * HB_gain_ref, 6);
  1405. HB_gain = HB_gain < (opus_val32)Q15ONE*6/7 ? HB_gain + Q15ONE/7 : Q15ONE;
  1406. }
  1407. } else {
  1408. /* SILK gets all bits */
  1409. st->silk_mode.bitRate = total_bitRate;
  1410. }
  1411. /* Surround masking for SILK */
  1412. if (st->energy_masking && st->use_vbr && !st->lfe)
  1413. {
  1414. opus_val32 mask_sum=0;
  1415. opus_val16 masking_depth;
  1416. opus_int32 rate_offset;
  1417. int c;
  1418. int end = 17;
  1419. opus_int16 srate = 16000;
  1420. if (st->bandwidth == OPUS_BANDWIDTH_NARROWBAND)
  1421. {
  1422. end = 13;
  1423. srate = 8000;
  1424. } else if (st->bandwidth == OPUS_BANDWIDTH_MEDIUMBAND)
  1425. {
  1426. end = 15;
  1427. srate = 12000;
  1428. }
  1429. for (c=0;c<st->channels;c++)
  1430. {
  1431. for(i=0;i<end;i++)
  1432. {
  1433. opus_val16 mask;
  1434. mask = MAX16(MIN16(st->energy_masking[21*c+i],
  1435. QCONST16(.5f, DB_SHIFT)), -QCONST16(2.0f, DB_SHIFT));
  1436. if (mask > 0)
  1437. mask = HALF16(mask);
  1438. mask_sum += mask;
  1439. }
  1440. }
  1441. /* Conservative rate reduction, we cut the masking in half */
  1442. masking_depth = mask_sum / end*st->channels;
  1443. masking_depth += QCONST16(.2f, DB_SHIFT);
  1444. rate_offset = (opus_int32)PSHR32(MULT16_16(srate, masking_depth), DB_SHIFT);
  1445. rate_offset = MAX32(rate_offset, -2*st->silk_mode.bitRate/3);
  1446. /* Split the rate change between the SILK and CELT part for hybrid. */
  1447. if (st->bandwidth==OPUS_BANDWIDTH_SUPERWIDEBAND || st->bandwidth==OPUS_BANDWIDTH_FULLBAND)
  1448. st->silk_mode.bitRate += 3*rate_offset/5;
  1449. else
  1450. st->silk_mode.bitRate += rate_offset;
  1451. bytes_target += rate_offset * frame_size / (8 * st->Fs);
  1452. }
  1453. st->silk_mode.payloadSize_ms = 1000 * frame_size / st->Fs;
  1454. st->silk_mode.nChannelsAPI = st->channels;
  1455. st->silk_mode.nChannelsInternal = st->stream_channels;
  1456. if (curr_bandwidth == OPUS_BANDWIDTH_NARROWBAND) {
  1457. st->silk_mode.desiredInternalSampleRate = 8000;
  1458. } else if (curr_bandwidth == OPUS_BANDWIDTH_MEDIUMBAND) {
  1459. st->silk_mode.desiredInternalSampleRate = 12000;
  1460. } else {
  1461. silk_assert( st->mode == MODE_HYBRID || curr_bandwidth == OPUS_BANDWIDTH_WIDEBAND );
  1462. st->silk_mode.desiredInternalSampleRate = 16000;
  1463. }
  1464. if( st->mode == MODE_HYBRID ) {
  1465. /* Don't allow bandwidth reduction at lowest bitrates in hybrid mode */
  1466. st->silk_mode.minInternalSampleRate = 16000;
  1467. } else {
  1468. st->silk_mode.minInternalSampleRate = 8000;
  1469. }
  1470. if (st->mode == MODE_SILK_ONLY)
  1471. {
  1472. opus_int32 effective_max_rate = max_rate;
  1473. st->silk_mode.maxInternalSampleRate = 16000;
  1474. if (frame_rate > 50)
  1475. effective_max_rate = effective_max_rate*2/3;
  1476. if (effective_max_rate < 13000)
  1477. {
  1478. st->silk_mode.maxInternalSampleRate = 12000;
  1479. st->silk_mode.desiredInternalSampleRate = IMIN(12000, st->silk_mode.desiredInternalSampleRate);
  1480. }
  1481. if (effective_max_rate < 9600)
  1482. {
  1483. st->silk_mode.maxInternalSampleRate = 8000;
  1484. st->silk_mode.desiredInternalSampleRate = IMIN(8000, st->silk_mode.desiredInternalSampleRate);
  1485. }
  1486. } else {
  1487. st->silk_mode.maxInternalSampleRate = 16000;
  1488. }
  1489. st->silk_mode.useCBR = !st->use_vbr;
  1490. /* Call SILK encoder for the low band */
  1491. nBytes = IMIN(1275, max_data_bytes-1-redundancy_bytes);
  1492. st->silk_mode.maxBits = nBytes*8;
  1493. /* Only allow up to 90% of the bits for hybrid mode*/
  1494. if (st->mode == MODE_HYBRID)
  1495. st->silk_mode.maxBits = (opus_int32)st->silk_mode.maxBits*9/10;
  1496. if (st->silk_mode.useCBR)
  1497. {
  1498. st->silk_mode.maxBits = (st->silk_mode.bitRate * frame_size / (st->Fs * 8))*8;
  1499. /* Reduce the initial target to make it easier to reach the CBR rate */
  1500. st->silk_mode.bitRate = IMAX(1, st->silk_mode.bitRate-2000);
  1501. }
  1502. if (prefill)
  1503. {
  1504. opus_int32 zero=0;
  1505. int prefill_offset;
  1506. /* Use a smooth onset for the SILK prefill to avoid the encoder trying to encode
  1507. a discontinuity. The exact location is what we need to avoid leaving any "gap"
  1508. in the audio when mixing with the redundant CELT frame. Here we can afford to
  1509. overwrite st->delay_buffer because the only thing that uses it before it gets
  1510. rewritten is tmp_prefill[] and even then only the part after the ramp really
  1511. gets used (rather than sent to the encoder and discarded) */
  1512. prefill_offset = st->channels*(st->encoder_buffer-st->delay_compensation-st->Fs/400);
  1513. gain_fade(st->delay_buffer+prefill_offset, st->delay_buffer+prefill_offset,
  1514. 0, Q15ONE, celt_mode->overlap, st->Fs/400, st->channels, celt_mode->window, st->Fs);
  1515. OPUS_CLEAR(st->delay_buffer, prefill_offset);
  1516. #ifdef FIXED_POINT
  1517. pcm_silk = st->delay_buffer;
  1518. #else
  1519. for (i=0;i<st->encoder_buffer*st->channels;i++)
  1520. pcm_silk[i] = FLOAT2INT16(st->delay_buffer[i]);
  1521. #endif
  1522. silk_Encode( silk_enc, &st->silk_mode, pcm_silk, st->encoder_buffer, NULL, &zero, 1 );
  1523. }
  1524. #ifdef FIXED_POINT
  1525. pcm_silk = pcm_buf+total_buffer*st->channels;
  1526. #else
  1527. for (i=0;i<frame_size*st->channels;i++)
  1528. pcm_silk[i] = FLOAT2INT16(pcm_buf[total_buffer*st->channels + i]);
  1529. #endif
  1530. ret = silk_Encode( silk_enc, &st->silk_mode, pcm_silk, frame_size, &enc, &nBytes, 0 );
  1531. if( ret ) {
  1532. /*fprintf (stderr, "SILK encode error: %d\n", ret);*/
  1533. /* Handle error */
  1534. RESTORE_STACK;
  1535. return OPUS_INTERNAL_ERROR;
  1536. }
  1537. if (nBytes==0)
  1538. {
  1539. st->rangeFinal = 0;
  1540. data[-1] = gen_toc(st->mode, st->Fs/frame_size, curr_bandwidth, st->stream_channels);
  1541. RESTORE_STACK;
  1542. return 1;
  1543. }
  1544. /* Extract SILK internal bandwidth for signaling in first byte */
  1545. if( st->mode == MODE_SILK_ONLY ) {
  1546. if( st->silk_mode.internalSampleRate == 8000 ) {
  1547. curr_bandwidth = OPUS_BANDWIDTH_NARROWBAND;
  1548. } else if( st->silk_mode.internalSampleRate == 12000 ) {
  1549. curr_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
  1550. } else if( st->silk_mode.internalSampleRate == 16000 ) {
  1551. curr_bandwidth = OPUS_BANDWIDTH_WIDEBAND;
  1552. }
  1553. } else {
  1554. silk_assert( st->silk_mode.internalSampleRate == 16000 );
  1555. }
  1556. st->silk_mode.opusCanSwitch = st->silk_mode.switchReady;
  1557. /* FIXME: How do we allocate the redundancy for CBR? */
  1558. if (st->silk_mode.opusCanSwitch)
  1559. {
  1560. redundancy = 1;
  1561. celt_to_silk = 0;
  1562. st->silk_bw_switch = 1;
  1563. }
  1564. }
  1565. /* CELT processing */
  1566. {
  1567. int endband=21;
  1568. switch(curr_bandwidth)
  1569. {
  1570. case OPUS_BANDWIDTH_NARROWBAND:
  1571. endband = 13;
  1572. break;
  1573. case OPUS_BANDWIDTH_MEDIUMBAND:
  1574. case OPUS_BANDWIDTH_WIDEBAND:
  1575. endband = 17;
  1576. break;
  1577. case OPUS_BANDWIDTH_SUPERWIDEBAND:
  1578. endband = 19;
  1579. break;
  1580. case OPUS_BANDWIDTH_FULLBAND:
  1581. endband = 21;
  1582. break;
  1583. }
  1584. celt_encoder_ctl(celt_enc, CELT_SET_END_BAND(endband));
  1585. celt_encoder_ctl(celt_enc, CELT_SET_CHANNELS(st->stream_channels));
  1586. }
  1587. celt_encoder_ctl(celt_enc, OPUS_SET_BITRATE(OPUS_BITRATE_MAX));
  1588. if (st->mode != MODE_SILK_ONLY)
  1589. {
  1590. opus_val32 celt_pred=2;
  1591. celt_encoder_ctl(celt_enc, OPUS_SET_VBR(0));
  1592. /* We may still decide to disable prediction later */
  1593. if (st->silk_mode.reducedDependency)
  1594. celt_pred = 0;
  1595. celt_encoder_ctl(celt_enc, CELT_SET_PREDICTION(celt_pred));
  1596. if (st->mode == MODE_HYBRID)
  1597. {
  1598. int len;
  1599. len = (ec_tell(&enc)+7)>>3;
  1600. if (redundancy)
  1601. len += st->mode == MODE_HYBRID ? 3 : 1;
  1602. if( st->use_vbr ) {
  1603. nb_compr_bytes = len + bytes_target - (st->silk_mode.bitRate * frame_size) / (8 * st->Fs);
  1604. } else {
  1605. /* check if SILK used up too much */
  1606. nb_compr_bytes = len > bytes_target ? len : bytes_target;
  1607. }
  1608. } else {
  1609. if (st->use_vbr)
  1610. {
  1611. opus_int32 bonus=0;
  1612. #ifndef DISABLE_FLOAT_API
  1613. if (st->variable_duration==OPUS_FRAMESIZE_VARIABLE && frame_size != st->Fs/50)
  1614. {
  1615. bonus = (60*st->stream_channels+40)*(st->Fs/frame_size-50);
  1616. if (analysis_info.valid)
  1617. bonus = (opus_int32)(bonus*(1.f+.5f*analysis_info.tonality));
  1618. }
  1619. #endif
  1620. celt_encoder_ctl(celt_enc, OPUS_SET_VBR(1));
  1621. celt_encoder_ctl(celt_enc, OPUS_SET_VBR_CONSTRAINT(st->vbr_constraint));
  1622. celt_encoder_ctl(celt_enc, OPUS_SET_BITRATE(st->bitrate_bps+bonus));
  1623. nb_compr_bytes = max_data_bytes-1-redundancy_bytes;
  1624. } else {
  1625. nb_compr_bytes = bytes_target;
  1626. }
  1627. }
  1628. } else {
  1629. nb_compr_bytes = 0;
  1630. }
  1631. ALLOC(tmp_prefill, st->channels*st->Fs/400, opus_val16);
  1632. if (st->mode != MODE_SILK_ONLY && st->mode != st->prev_mode && st->prev_mode > 0)
  1633. {
  1634. OPUS_COPY(tmp_prefill, &st->delay_buffer[(st->encoder_buffer-total_buffer-st->Fs/400)*st->channels], st->channels*st->Fs/400);
  1635. }
  1636. if (st->channels*(st->encoder_buffer-(frame_size+total_buffer)) > 0)
  1637. {
  1638. OPUS_MOVE(st->delay_buffer, &st->delay_buffer[st->channels*frame_size], st->channels*(st->encoder_buffer-frame_size-total_buffer));
  1639. OPUS_COPY(&st->delay_buffer[st->channels*(st->encoder_buffer-frame_size-total_buffer)],
  1640. &pcm_buf[0],
  1641. (frame_size+total_buffer)*st->channels);
  1642. } else {
  1643. OPUS_COPY(st->delay_buffer, &pcm_buf[(frame_size+total_buffer-st->encoder_buffer)*st->channels], st->encoder_buffer*st->channels);
  1644. }
  1645. /* gain_fade() and stereo_fade() need to be after the buffer copying
  1646. because we don't want any of this to affect the SILK part */
  1647. if( st->prev_HB_gain < Q15ONE || HB_gain < Q15ONE ) {
  1648. gain_fade(pcm_buf, pcm_buf,
  1649. st->prev_HB_gain, HB_gain, celt_mode->overlap, frame_size, st->channels, celt_mode->window, st->Fs);
  1650. }
  1651. st->prev_HB_gain = HB_gain;
  1652. if (st->mode != MODE_HYBRID || st->stream_channels==1)
  1653. st->silk_mode.stereoWidth_Q14 = IMIN((1<<14),2*IMAX(0,equiv_rate-30000));
  1654. if( !st->energy_masking && st->channels == 2 ) {
  1655. /* Apply stereo width reduction (at low bitrates) */
  1656. if( st->hybrid_stereo_width_Q14 < (1 << 14) || st->silk_mode.stereoWidth_Q14 < (1 << 14) ) {
  1657. opus_val16 g1, g2;
  1658. g1 = st->hybrid_stereo_width_Q14;
  1659. g2 = (opus_val16)(st->silk_mode.stereoWidth_Q14);
  1660. #ifdef FIXED_POINT
  1661. g1 = g1==16384 ? Q15ONE : SHL16(g1,1);
  1662. g2 = g2==16384 ? Q15ONE : SHL16(g2,1);
  1663. #else
  1664. g1 *= (1.f/16384);
  1665. g2 *= (1.f/16384);
  1666. #endif
  1667. stereo_fade(pcm_buf, pcm_buf, g1, g2, celt_mode->overlap,
  1668. frame_size, st->channels, celt_mode->window, st->Fs);
  1669. st->hybrid_stereo_width_Q14 = st->silk_mode.stereoWidth_Q14;
  1670. }
  1671. }
  1672. if ( st->mode != MODE_CELT_ONLY && ec_tell(&enc)+17+20*(st->mode == MODE_HYBRID) <= 8*(max_data_bytes-1))
  1673. {
  1674. /* For SILK mode, the redundancy is inferred from the length */
  1675. if (st->mode == MODE_HYBRID && (redundancy || ec_tell(&enc)+37 <= 8*nb_compr_bytes))
  1676. ec_enc_bit_logp(&enc, redundancy, 12);
  1677. if (redundancy)
  1678. {
  1679. int max_redundancy;
  1680. ec_enc_bit_logp(&enc, celt_to_silk, 1);
  1681. if (st->mode == MODE_HYBRID)
  1682. max_redundancy = (max_data_bytes-1)-nb_compr_bytes;
  1683. else
  1684. max_redundancy = (max_data_bytes-1)-((ec_tell(&enc)+7)>>3);
  1685. /* Target the same bit-rate for redundancy as for the rest,
  1686. up to a max of 257 bytes */
  1687. redundancy_bytes = IMIN(max_redundancy, st->bitrate_bps/1600);
  1688. redundancy_bytes = IMIN(257, IMAX(2, redundancy_bytes));
  1689. if (st->mode == MODE_HYBRID)
  1690. ec_enc_uint(&enc, redundancy_bytes-2, 256);
  1691. }
  1692. } else {
  1693. redundancy = 0;
  1694. }
  1695. if (!redundancy)
  1696. {
  1697. st->silk_bw_switch = 0;
  1698. redundancy_bytes = 0;
  1699. }
  1700. if (st->mode != MODE_CELT_ONLY)start_band=17;
  1701. if (st->mode == MODE_SILK_ONLY)
  1702. {
  1703. ret = (ec_tell(&enc)+7)>>3;
  1704. ec_enc_done(&enc);
  1705. nb_compr_bytes = ret;
  1706. } else {
  1707. nb_compr_bytes = IMIN((max_data_bytes-1)-redundancy_bytes, nb_compr_bytes);
  1708. ec_enc_shrink(&enc, nb_compr_bytes);
  1709. }
  1710. #ifndef DISABLE_FLOAT_API
  1711. if (redundancy || st->mode != MODE_SILK_ONLY)
  1712. celt_encoder_ctl(celt_enc, CELT_SET_ANALYSIS(&analysis_info));
  1713. #endif
  1714. /* 5 ms redundant frame for CELT->SILK */
  1715. if (redundancy && celt_to_silk)
  1716. {
  1717. int err;
  1718. celt_encoder_ctl(celt_enc, CELT_SET_START_BAND(0));
  1719. celt_encoder_ctl(celt_enc, OPUS_SET_VBR(0));
  1720. err = celt_encode_with_ec(celt_enc, pcm_buf, st->Fs/200, data+nb_compr_bytes, redundancy_bytes, NULL);
  1721. if (err < 0)
  1722. {
  1723. RESTORE_STACK;
  1724. return OPUS_INTERNAL_ERROR;
  1725. }
  1726. celt_encoder_ctl(celt_enc, OPUS_GET_FINAL_RANGE(&redundant_rng));
  1727. celt_encoder_ctl(celt_enc, OPUS_RESET_STATE);
  1728. }
  1729. celt_encoder_ctl(celt_enc, CELT_SET_START_BAND(start_band));
  1730. if (st->mode != MODE_SILK_ONLY)
  1731. {
  1732. if (st->mode != st->prev_mode && st->prev_mode > 0)
  1733. {
  1734. unsigned char dummy[2];
  1735. celt_encoder_ctl(celt_enc, OPUS_RESET_STATE);
  1736. /* Prefilling */
  1737. celt_encode_with_ec(celt_enc, tmp_prefill, st->Fs/400, dummy, 2, NULL);
  1738. celt_encoder_ctl(celt_enc, CELT_SET_PREDICTION(0));
  1739. }
  1740. /* If false, we already busted the budget and we'll end up with a "PLC packet" */
  1741. if (ec_tell(&enc) <= 8*nb_compr_bytes)
  1742. {
  1743. ret = celt_encode_with_ec(celt_enc, pcm_buf, frame_size, NULL, nb_compr_bytes, &enc);
  1744. if (ret < 0)
  1745. {
  1746. RESTORE_STACK;
  1747. return OPUS_INTERNAL_ERROR;
  1748. }
  1749. }
  1750. }
  1751. /* 5 ms redundant frame for SILK->CELT */
  1752. if (redundancy && !celt_to_silk)
  1753. {
  1754. int err;
  1755. unsigned char dummy[2];
  1756. int N2, N4;
  1757. N2 = st->Fs/200;
  1758. N4 = st->Fs/400;
  1759. celt_encoder_ctl(celt_enc, OPUS_RESET_STATE);
  1760. celt_encoder_ctl(celt_enc, CELT_SET_START_BAND(0));
  1761. celt_encoder_ctl(celt_enc, CELT_SET_PREDICTION(0));
  1762. /* NOTE: We could speed this up slightly (at the expense of code size) by just adding a function that prefills the buffer */
  1763. celt_encode_with_ec(celt_enc, pcm_buf+st->channels*(frame_size-N2-N4), N4, dummy, 2, NULL);
  1764. err = celt_encode_with_ec(celt_enc, pcm_buf+st->channels*(frame_size-N2), N2, data+nb_compr_bytes, redundancy_bytes, NULL);
  1765. if (err < 0)
  1766. {
  1767. RESTORE_STACK;
  1768. return OPUS_INTERNAL_ERROR;
  1769. }
  1770. celt_encoder_ctl(celt_enc, OPUS_GET_FINAL_RANGE(&redundant_rng));
  1771. }
  1772. /* Signalling the mode in the first byte */
  1773. data--;
  1774. data[0] = gen_toc(st->mode, st->Fs/frame_size, curr_bandwidth, st->stream_channels);
  1775. st->rangeFinal = enc.rng ^ redundant_rng;
  1776. if (to_celt)
  1777. st->prev_mode = MODE_CELT_ONLY;
  1778. else
  1779. st->prev_mode = st->mode;
  1780. st->prev_channels = st->stream_channels;
  1781. st->prev_framesize = frame_size;
  1782. st->first = 0;
  1783. /* In the unlikely case that the SILK encoder busted its target, tell
  1784. the decoder to call the PLC */
  1785. if (ec_tell(&enc) > (max_data_bytes-1)*8)
  1786. {
  1787. if (max_data_bytes < 2)
  1788. {
  1789. RESTORE_STACK;
  1790. return OPUS_BUFFER_TOO_SMALL;
  1791. }
  1792. data[1] = 0;
  1793. ret = 1;
  1794. st->rangeFinal = 0;
  1795. } else if (st->mode==MODE_SILK_ONLY&&!redundancy)
  1796. {
  1797. /*When in LPC only mode it's perfectly
  1798. reasonable to strip off trailing zero bytes as
  1799. the required range decoder behavior is to
  1800. fill these in. This can't be done when the MDCT
  1801. modes are used because the decoder needs to know
  1802. the actual length for allocation purposes.*/
  1803. while(ret>2&&data[ret]==0)ret--;
  1804. }
  1805. /* Count ToC and redundancy */
  1806. ret += 1+redundancy_bytes;
  1807. if (!st->use_vbr)
  1808. {
  1809. if (opus_packet_pad(data, ret, max_data_bytes) != OPUS_OK)
  1810. {
  1811. RESTORE_STACK;
  1812. return OPUS_INTERNAL_ERROR;
  1813. }
  1814. ret = max_data_bytes;
  1815. }
  1816. RESTORE_STACK;
  1817. return ret;
  1818. }
  1819. #ifdef FIXED_POINT
  1820. #ifndef DISABLE_FLOAT_API
  1821. opus_int32 opus_encode_float(OpusEncoder *st, const float *pcm, int analysis_frame_size,
  1822. unsigned char *data, opus_int32 max_data_bytes)
  1823. {
  1824. int i, ret;
  1825. int frame_size;
  1826. int delay_compensation;
  1827. VARDECL(opus_int16, in);
  1828. ALLOC_STACK;
  1829. if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
  1830. delay_compensation = 0;
  1831. else
  1832. delay_compensation = st->delay_compensation;
  1833. frame_size = compute_frame_size(pcm, analysis_frame_size,
  1834. st->variable_duration, st->channels, st->Fs, st->bitrate_bps,
  1835. delay_compensation, downmix_float, st->analysis.subframe_mem);
  1836. ALLOC(in, frame_size*st->channels, opus_int16);
  1837. for (i=0;i<frame_size*st->channels;i++)
  1838. in[i] = FLOAT2INT16(pcm[i]);
  1839. ret = opus_encode_native(st, in, frame_size, data, max_data_bytes, 16,
  1840. pcm, analysis_frame_size, 0, -2, st->channels, downmix_float, 1);
  1841. RESTORE_STACK;
  1842. return ret;
  1843. }
  1844. #endif
  1845. opus_int32 opus_encode(OpusEncoder *st, const opus_int16 *pcm, int analysis_frame_size,
  1846. unsigned char *data, opus_int32 out_data_bytes)
  1847. {
  1848. int frame_size;
  1849. int delay_compensation;
  1850. if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
  1851. delay_compensation = 0;
  1852. else
  1853. delay_compensation = st->delay_compensation;
  1854. frame_size = compute_frame_size(pcm, analysis_frame_size,
  1855. st->variable_duration, st->channels, st->Fs, st->bitrate_bps,
  1856. delay_compensation, downmix_int
  1857. #ifndef DISABLE_FLOAT_API
  1858. , st->analysis.subframe_mem
  1859. #endif
  1860. );
  1861. return opus_encode_native(st, pcm, frame_size, data, out_data_bytes, 16,
  1862. pcm, analysis_frame_size, 0, -2, st->channels, downmix_int, 0);
  1863. }
  1864. #else
  1865. opus_int32 opus_encode(OpusEncoder *st, const opus_int16 *pcm, int analysis_frame_size,
  1866. unsigned char *data, opus_int32 max_data_bytes)
  1867. {
  1868. int i, ret;
  1869. int frame_size;
  1870. int delay_compensation;
  1871. VARDECL(float, in);
  1872. ALLOC_STACK;
  1873. if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
  1874. delay_compensation = 0;
  1875. else
  1876. delay_compensation = st->delay_compensation;
  1877. frame_size = compute_frame_size(pcm, analysis_frame_size,
  1878. st->variable_duration, st->channels, st->Fs, st->bitrate_bps,
  1879. delay_compensation, downmix_int, st->analysis.subframe_mem);
  1880. ALLOC(in, frame_size*st->channels, float);
  1881. for (i=0;i<frame_size*st->channels;i++)
  1882. in[i] = (1.0f/32768)*pcm[i];
  1883. ret = opus_encode_native(st, in, frame_size, data, max_data_bytes, 16,
  1884. pcm, analysis_frame_size, 0, -2, st->channels, downmix_int, 0);
  1885. RESTORE_STACK;
  1886. return ret;
  1887. }
  1888. opus_int32 opus_encode_float(OpusEncoder *st, const float *pcm, int analysis_frame_size,
  1889. unsigned char *data, opus_int32 out_data_bytes)
  1890. {
  1891. int frame_size;
  1892. int delay_compensation;
  1893. if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
  1894. delay_compensation = 0;
  1895. else
  1896. delay_compensation = st->delay_compensation;
  1897. frame_size = compute_frame_size(pcm, analysis_frame_size,
  1898. st->variable_duration, st->channels, st->Fs, st->bitrate_bps,
  1899. delay_compensation, downmix_float, st->analysis.subframe_mem);
  1900. return opus_encode_native(st, pcm, frame_size, data, out_data_bytes, 24,
  1901. pcm, analysis_frame_size, 0, -2, st->channels, downmix_float, 1);
  1902. }
  1903. #endif
  1904. int opus_encoder_ctl(OpusEncoder *st, int request, ...)
  1905. {
  1906. int ret;
  1907. CELTEncoder *celt_enc;
  1908. va_list ap;
  1909. ret = OPUS_OK;
  1910. va_start(ap, request);
  1911. celt_enc = (CELTEncoder*)((char*)st+st->celt_enc_offset);
  1912. switch (request)
  1913. {
  1914. case OPUS_SET_APPLICATION_REQUEST:
  1915. {
  1916. opus_int32 value = va_arg(ap, opus_int32);
  1917. if ( (value != OPUS_APPLICATION_VOIP && value != OPUS_APPLICATION_AUDIO
  1918. && value != OPUS_APPLICATION_RESTRICTED_LOWDELAY)
  1919. || (!st->first && st->application != value))
  1920. {
  1921. ret = OPUS_BAD_ARG;
  1922. break;
  1923. }
  1924. st->application = value;
  1925. }
  1926. break;
  1927. case OPUS_GET_APPLICATION_REQUEST:
  1928. {
  1929. opus_int32 *value = va_arg(ap, opus_int32*);
  1930. if (!value)
  1931. {
  1932. goto bad_arg;
  1933. }
  1934. *value = st->application;
  1935. }
  1936. break;
  1937. case OPUS_SET_BITRATE_REQUEST:
  1938. {
  1939. opus_int32 value = va_arg(ap, opus_int32);
  1940. if (value != OPUS_AUTO && value != OPUS_BITRATE_MAX)
  1941. {
  1942. if (value <= 0)
  1943. goto bad_arg;
  1944. else if (value <= 500)
  1945. value = 500;
  1946. else if (value > (opus_int32)300000*st->channels)
  1947. value = (opus_int32)300000*st->channels;
  1948. }
  1949. st->user_bitrate_bps = value;
  1950. }
  1951. break;
  1952. case OPUS_GET_BITRATE_REQUEST:
  1953. {
  1954. opus_int32 *value = va_arg(ap, opus_int32*);
  1955. if (!value)
  1956. {
  1957. goto bad_arg;
  1958. }
  1959. *value = user_bitrate_to_bitrate(st, st->prev_framesize, 1276);
  1960. }
  1961. break;
  1962. case OPUS_SET_FORCE_CHANNELS_REQUEST:
  1963. {
  1964. opus_int32 value = va_arg(ap, opus_int32);
  1965. if((value<1 || value>st->channels) && value != OPUS_AUTO)
  1966. {
  1967. goto bad_arg;
  1968. }
  1969. st->force_channels = value;
  1970. }
  1971. break;
  1972. case OPUS_GET_FORCE_CHANNELS_REQUEST:
  1973. {
  1974. opus_int32 *value = va_arg(ap, opus_int32*);
  1975. if (!value)
  1976. {
  1977. goto bad_arg;
  1978. }
  1979. *value = st->force_channels;
  1980. }
  1981. break;
  1982. case OPUS_SET_MAX_BANDWIDTH_REQUEST:
  1983. {
  1984. opus_int32 value = va_arg(ap, opus_int32);
  1985. if (value < OPUS_BANDWIDTH_NARROWBAND || value > OPUS_BANDWIDTH_FULLBAND)
  1986. {
  1987. goto bad_arg;
  1988. }
  1989. st->max_bandwidth = value;
  1990. if (st->max_bandwidth == OPUS_BANDWIDTH_NARROWBAND) {
  1991. st->silk_mode.maxInternalSampleRate = 8000;
  1992. } else if (st->max_bandwidth == OPUS_BANDWIDTH_MEDIUMBAND) {
  1993. st->silk_mode.maxInternalSampleRate = 12000;
  1994. } else {
  1995. st->silk_mode.maxInternalSampleRate = 16000;
  1996. }
  1997. }
  1998. break;
  1999. case OPUS_GET_MAX_BANDWIDTH_REQUEST:
  2000. {
  2001. opus_int32 *value = va_arg(ap, opus_int32*);
  2002. if (!value)
  2003. {
  2004. goto bad_arg;
  2005. }
  2006. *value = st->max_bandwidth;
  2007. }
  2008. break;
  2009. case OPUS_SET_BANDWIDTH_REQUEST:
  2010. {
  2011. opus_int32 value = va_arg(ap, opus_int32);
  2012. if ((value < OPUS_BANDWIDTH_NARROWBAND || value > OPUS_BANDWIDTH_FULLBAND) && value != OPUS_AUTO)
  2013. {
  2014. goto bad_arg;
  2015. }
  2016. st->user_bandwidth = value;
  2017. if (st->user_bandwidth == OPUS_BANDWIDTH_NARROWBAND) {
  2018. st->silk_mode.maxInternalSampleRate = 8000;
  2019. } else if (st->user_bandwidth == OPUS_BANDWIDTH_MEDIUMBAND) {
  2020. st->silk_mode.maxInternalSampleRate = 12000;
  2021. } else {
  2022. st->silk_mode.maxInternalSampleRate = 16000;
  2023. }
  2024. }
  2025. break;
  2026. case OPUS_GET_BANDWIDTH_REQUEST:
  2027. {
  2028. opus_int32 *value = va_arg(ap, opus_int32*);
  2029. if (!value)
  2030. {
  2031. goto bad_arg;
  2032. }
  2033. *value = st->bandwidth;
  2034. }
  2035. break;
  2036. case OPUS_SET_DTX_REQUEST:
  2037. {
  2038. opus_int32 value = va_arg(ap, opus_int32);
  2039. if(value<0 || value>1)
  2040. {
  2041. goto bad_arg;
  2042. }
  2043. st->silk_mode.useDTX = value;
  2044. }
  2045. break;
  2046. case OPUS_GET_DTX_REQUEST:
  2047. {
  2048. opus_int32 *value = va_arg(ap, opus_int32*);
  2049. if (!value)
  2050. {
  2051. goto bad_arg;
  2052. }
  2053. *value = st->silk_mode.useDTX;
  2054. }
  2055. break;
  2056. case OPUS_SET_COMPLEXITY_REQUEST:
  2057. {
  2058. opus_int32 value = va_arg(ap, opus_int32);
  2059. if(value<0 || value>10)
  2060. {
  2061. goto bad_arg;
  2062. }
  2063. st->silk_mode.complexity = value;
  2064. celt_encoder_ctl(celt_enc, OPUS_SET_COMPLEXITY(value));
  2065. }
  2066. break;
  2067. case OPUS_GET_COMPLEXITY_REQUEST:
  2068. {
  2069. opus_int32 *value = va_arg(ap, opus_int32*);
  2070. if (!value)
  2071. {
  2072. goto bad_arg;
  2073. }
  2074. *value = st->silk_mode.complexity;
  2075. }
  2076. break;
  2077. case OPUS_SET_INBAND_FEC_REQUEST:
  2078. {
  2079. opus_int32 value = va_arg(ap, opus_int32);
  2080. if(value<0 || value>1)
  2081. {
  2082. goto bad_arg;
  2083. }
  2084. st->silk_mode.useInBandFEC = value;
  2085. }
  2086. break;
  2087. case OPUS_GET_INBAND_FEC_REQUEST:
  2088. {
  2089. opus_int32 *value = va_arg(ap, opus_int32*);
  2090. if (!value)
  2091. {
  2092. goto bad_arg;
  2093. }
  2094. *value = st->silk_mode.useInBandFEC;
  2095. }
  2096. break;
  2097. case OPUS_SET_PACKET_LOSS_PERC_REQUEST:
  2098. {
  2099. opus_int32 value = va_arg(ap, opus_int32);
  2100. if (value < 0 || value > 100)
  2101. {
  2102. goto bad_arg;
  2103. }
  2104. st->silk_mode.packetLossPercentage = value;
  2105. celt_encoder_ctl(celt_enc, OPUS_SET_PACKET_LOSS_PERC(value));
  2106. }
  2107. break;
  2108. case OPUS_GET_PACKET_LOSS_PERC_REQUEST:
  2109. {
  2110. opus_int32 *value = va_arg(ap, opus_int32*);
  2111. if (!value)
  2112. {
  2113. goto bad_arg;
  2114. }
  2115. *value = st->silk_mode.packetLossPercentage;
  2116. }
  2117. break;
  2118. case OPUS_SET_VBR_REQUEST:
  2119. {
  2120. opus_int32 value = va_arg(ap, opus_int32);
  2121. if(value<0 || value>1)
  2122. {
  2123. goto bad_arg;
  2124. }
  2125. st->use_vbr = value;
  2126. st->silk_mode.useCBR = 1-value;
  2127. }
  2128. break;
  2129. case OPUS_GET_VBR_REQUEST:
  2130. {
  2131. opus_int32 *value = va_arg(ap, opus_int32*);
  2132. if (!value)
  2133. {
  2134. goto bad_arg;
  2135. }
  2136. *value = st->use_vbr;
  2137. }
  2138. break;
  2139. case OPUS_SET_VOICE_RATIO_REQUEST:
  2140. {
  2141. opus_int32 value = va_arg(ap, opus_int32);
  2142. if (value<-1 || value>100)
  2143. {
  2144. goto bad_arg;
  2145. }
  2146. st->voice_ratio = value;
  2147. }
  2148. break;
  2149. case OPUS_GET_VOICE_RATIO_REQUEST:
  2150. {
  2151. opus_int32 *value = va_arg(ap, opus_int32*);
  2152. if (!value)
  2153. {
  2154. goto bad_arg;
  2155. }
  2156. *value = st->voice_ratio;
  2157. }
  2158. break;
  2159. case OPUS_SET_VBR_CONSTRAINT_REQUEST:
  2160. {
  2161. opus_int32 value = va_arg(ap, opus_int32);
  2162. if(value<0 || value>1)
  2163. {
  2164. goto bad_arg;
  2165. }
  2166. st->vbr_constraint = value;
  2167. }
  2168. break;
  2169. case OPUS_GET_VBR_CONSTRAINT_REQUEST:
  2170. {
  2171. opus_int32 *value = va_arg(ap, opus_int32*);
  2172. if (!value)
  2173. {
  2174. goto bad_arg;
  2175. }
  2176. *value = st->vbr_constraint;
  2177. }
  2178. break;
  2179. case OPUS_SET_SIGNAL_REQUEST:
  2180. {
  2181. opus_int32 value = va_arg(ap, opus_int32);
  2182. if(value!=OPUS_AUTO && value!=OPUS_SIGNAL_VOICE && value!=OPUS_SIGNAL_MUSIC)
  2183. {
  2184. goto bad_arg;
  2185. }
  2186. st->signal_type = value;
  2187. }
  2188. break;
  2189. case OPUS_GET_SIGNAL_REQUEST:
  2190. {
  2191. opus_int32 *value = va_arg(ap, opus_int32*);
  2192. if (!value)
  2193. {
  2194. goto bad_arg;
  2195. }
  2196. *value = st->signal_type;
  2197. }
  2198. break;
  2199. case OPUS_GET_LOOKAHEAD_REQUEST:
  2200. {
  2201. opus_int32 *value = va_arg(ap, opus_int32*);
  2202. if (!value)
  2203. {
  2204. goto bad_arg;
  2205. }
  2206. *value = st->Fs/400;
  2207. if (st->application != OPUS_APPLICATION_RESTRICTED_LOWDELAY)
  2208. *value += st->delay_compensation;
  2209. }
  2210. break;
  2211. case OPUS_GET_SAMPLE_RATE_REQUEST:
  2212. {
  2213. opus_int32 *value = va_arg(ap, opus_int32*);
  2214. if (!value)
  2215. {
  2216. goto bad_arg;
  2217. }
  2218. *value = st->Fs;
  2219. }
  2220. break;
  2221. case OPUS_GET_FINAL_RANGE_REQUEST:
  2222. {
  2223. opus_uint32 *value = va_arg(ap, opus_uint32*);
  2224. if (!value)
  2225. {
  2226. goto bad_arg;
  2227. }
  2228. *value = st->rangeFinal;
  2229. }
  2230. break;
  2231. case OPUS_SET_LSB_DEPTH_REQUEST:
  2232. {
  2233. opus_int32 value = va_arg(ap, opus_int32);
  2234. if (value<8 || value>24)
  2235. {
  2236. goto bad_arg;
  2237. }
  2238. st->lsb_depth=value;
  2239. }
  2240. break;
  2241. case OPUS_GET_LSB_DEPTH_REQUEST:
  2242. {
  2243. opus_int32 *value = va_arg(ap, opus_int32*);
  2244. if (!value)
  2245. {
  2246. goto bad_arg;
  2247. }
  2248. *value = st->lsb_depth;
  2249. }
  2250. break;
  2251. case OPUS_SET_EXPERT_FRAME_DURATION_REQUEST:
  2252. {
  2253. opus_int32 value = va_arg(ap, opus_int32);
  2254. if (value != OPUS_FRAMESIZE_ARG && value != OPUS_FRAMESIZE_2_5_MS &&
  2255. value != OPUS_FRAMESIZE_5_MS && value != OPUS_FRAMESIZE_10_MS &&
  2256. value != OPUS_FRAMESIZE_20_MS && value != OPUS_FRAMESIZE_40_MS &&
  2257. value != OPUS_FRAMESIZE_60_MS && value != OPUS_FRAMESIZE_VARIABLE)
  2258. {
  2259. goto bad_arg;
  2260. }
  2261. st->variable_duration = value;
  2262. celt_encoder_ctl(celt_enc, OPUS_SET_EXPERT_FRAME_DURATION(value));
  2263. }
  2264. break;
  2265. case OPUS_GET_EXPERT_FRAME_DURATION_REQUEST:
  2266. {
  2267. opus_int32 *value = va_arg(ap, opus_int32*);
  2268. if (!value)
  2269. {
  2270. goto bad_arg;
  2271. }
  2272. *value = st->variable_duration;
  2273. }
  2274. break;
  2275. case OPUS_SET_PREDICTION_DISABLED_REQUEST:
  2276. {
  2277. opus_int32 value = va_arg(ap, opus_int32);
  2278. if (value > 1 || value < 0)
  2279. goto bad_arg;
  2280. st->silk_mode.reducedDependency = value;
  2281. }
  2282. break;
  2283. case OPUS_GET_PREDICTION_DISABLED_REQUEST:
  2284. {
  2285. opus_int32 *value = va_arg(ap, opus_int32*);
  2286. if (!value)
  2287. goto bad_arg;
  2288. *value = st->silk_mode.reducedDependency;
  2289. }
  2290. break;
  2291. case OPUS_RESET_STATE:
  2292. {
  2293. void *silk_enc;
  2294. silk_EncControlStruct dummy;
  2295. char *start;
  2296. silk_enc = (char*)st+st->silk_enc_offset;
  2297. #ifndef DISABLE_FLOAT_API
  2298. tonality_analysis_reset(&st->analysis);
  2299. #endif
  2300. start = (char*)&st->OPUS_ENCODER_RESET_START;
  2301. OPUS_CLEAR(start, sizeof(OpusEncoder) - (start - (char*)st));
  2302. celt_encoder_ctl(celt_enc, OPUS_RESET_STATE);
  2303. silk_InitEncoder( silk_enc, st->arch, &dummy );
  2304. st->stream_channels = st->channels;
  2305. st->hybrid_stereo_width_Q14 = 1 << 14;
  2306. st->prev_HB_gain = Q15ONE;
  2307. st->first = 1;
  2308. st->mode = MODE_HYBRID;
  2309. st->bandwidth = OPUS_BANDWIDTH_FULLBAND;
  2310. st->variable_HP_smth2_Q15 = silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 );
  2311. }
  2312. break;
  2313. case OPUS_SET_FORCE_MODE_REQUEST:
  2314. {
  2315. opus_int32 value = va_arg(ap, opus_int32);
  2316. if ((value < MODE_SILK_ONLY || value > MODE_CELT_ONLY) && value != OPUS_AUTO)
  2317. {
  2318. goto bad_arg;
  2319. }
  2320. st->user_forced_mode = value;
  2321. }
  2322. break;
  2323. case OPUS_SET_LFE_REQUEST:
  2324. {
  2325. opus_int32 value = va_arg(ap, opus_int32);
  2326. st->lfe = value;
  2327. ret = celt_encoder_ctl(celt_enc, OPUS_SET_LFE(value));
  2328. }
  2329. break;
  2330. case OPUS_SET_ENERGY_MASK_REQUEST:
  2331. {
  2332. opus_val16 *value = va_arg(ap, opus_val16*);
  2333. st->energy_masking = value;
  2334. ret = celt_encoder_ctl(celt_enc, OPUS_SET_ENERGY_MASK(value));
  2335. }
  2336. break;
  2337. case CELT_GET_MODE_REQUEST:
  2338. {
  2339. const CELTMode ** value = va_arg(ap, const CELTMode**);
  2340. if (!value)
  2341. {
  2342. goto bad_arg;
  2343. }
  2344. ret = celt_encoder_ctl(celt_enc, CELT_GET_MODE(value));
  2345. }
  2346. break;
  2347. default:
  2348. /* fprintf(stderr, "unknown opus_encoder_ctl() request: %d", request);*/
  2349. ret = OPUS_UNIMPLEMENTED;
  2350. break;
  2351. }
  2352. va_end(ap);
  2353. return ret;
  2354. bad_arg:
  2355. va_end(ap);
  2356. return OPUS_BAD_ARG;
  2357. }
  2358. void opus_encoder_destroy(OpusEncoder *st)
  2359. {
  2360. opus_free(st);
  2361. }