flac_stream_encoder.c 169 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296
  1. /* libFLAC - Free Lossless Audio Codec library
  2. * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007 Josh Coalson
  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. *
  8. * - Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. *
  11. * - Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. *
  15. * - Neither the name of the Xiph.org Foundation nor the names of its
  16. * contributors may be used to endorse or promote products derived from
  17. * this software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
  23. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  24. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  25. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. #if HAVE_CONFIG_H
  32. # include <config.h>
  33. #endif
  34. #if defined (_WIN32)
  35. #include <io.h> /* for _setmode() */
  36. #include <fcntl.h> /* for _O_BINARY */
  37. #endif
  38. #include <limits.h>
  39. #include <stdio.h>
  40. #include <stdlib.h> /* for malloc() */
  41. #include <string.h> /* for memcpy() */
  42. #include <sys/types.h> /* for off_t */
  43. #include "flac_FLAC_assert.h"
  44. #include "flac_FLAC_stream_decoder.h"
  45. #include "flac_share_alloc.h"
  46. #include "flac_protected_stream_encoder.h"
  47. #include "flac_private_autocpu.h"
  48. #include "flac_private_bitwriter.h"
  49. #include "flac_private_bitmath.h"
  50. #include "flac_private_crc.h"
  51. #include "flac_private_cpu.h"
  52. #include "flac_private_fixed.h"
  53. #include "flac_private_format.h"
  54. #include "flac_private_lpc.h"
  55. #include "flac_private_md5.h"
  56. #include "flac_private_memory.h"
  57. #if FLAC__HAS_OGG
  58. #include "private/ogg_helper.h"
  59. #include "private/ogg_mapping.h"
  60. #endif
  61. #include "flac_private_stream_encoder_framing.h"
  62. #include "flac_private_window.h"
  63. #ifndef FLaC__INLINE
  64. #define FLaC__INLINE
  65. #endif
  66. #ifdef min
  67. #undef min
  68. #endif
  69. #define min(x,y) ((x)<(y)?(x):(y))
  70. #ifdef max
  71. #undef max
  72. #endif
  73. #define max(x,y) ((x)>(y)?(x):(y))
  74. /* Exact Rice codeword length calculation is off by default. The simple
  75. * (and fast) estimation (of how many bits a residual value will be
  76. * encoded with) in this encoder is very good, almost always yielding
  77. * compression within 0.1% of exact calculation.
  78. */
  79. #undef EXACT_RICE_BITS_CALCULATION
  80. /* Rice parameter searching is off by default. The simple (and fast)
  81. * parameter estimation in this encoder is very good, almost always
  82. * yielding compression within 0.1% of the optimal parameters.
  83. */
  84. #undef ENABLE_RICE_PARAMETER_SEARCH
  85. typedef struct {
  86. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  87. unsigned size; /* of each data[] in samples */
  88. unsigned tail;
  89. } verify_input_fifo;
  90. typedef struct {
  91. const FLAC__byte *data;
  92. unsigned capacity;
  93. unsigned bytes;
  94. } verify_output;
  95. typedef enum {
  96. ENCODER_IN_MAGIC = 0,
  97. ENCODER_IN_METADATA = 1,
  98. ENCODER_IN_AUDIO = 2
  99. } EncoderStateHint;
  100. static struct CompressionLevels {
  101. FLAC__bool do_mid_side_stereo;
  102. FLAC__bool loose_mid_side_stereo;
  103. unsigned max_lpc_order;
  104. unsigned qlp_coeff_precision;
  105. FLAC__bool do_qlp_coeff_prec_search;
  106. FLAC__bool do_escape_coding;
  107. FLAC__bool do_exhaustive_model_search;
  108. unsigned min_residual_partition_order;
  109. unsigned max_residual_partition_order;
  110. unsigned rice_parameter_search_dist;
  111. } compression_levels_[] = {
  112. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  113. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  114. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  115. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  116. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  117. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  118. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  119. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  120. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  121. };
  122. /***********************************************************************
  123. *
  124. * Private class method prototypes
  125. *
  126. ***********************************************************************/
  127. static void set_defaults_(FLAC__StreamEncoder *encoder);
  128. static void free_(FLAC__StreamEncoder *encoder);
  129. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  130. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  131. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  132. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  133. #if FLAC__HAS_OGG
  134. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  135. #endif
  136. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  137. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  138. static FLAC__bool process_subframe_(
  139. FLAC__StreamEncoder *encoder,
  140. unsigned min_partition_order,
  141. unsigned max_partition_order,
  142. const FLAC__FrameHeader *frame_header,
  143. unsigned subframe_bps,
  144. const FLAC__int32 integer_signal[],
  145. FLAC__Subframe *subframe[2],
  146. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  147. FLAC__int32 *residual[2],
  148. unsigned *best_subframe,
  149. unsigned *best_bits
  150. );
  151. static FLAC__bool add_subframe_(
  152. FLAC__StreamEncoder *encoder,
  153. unsigned blocksize,
  154. unsigned subframe_bps,
  155. const FLAC__Subframe *subframe,
  156. FLAC__BitWriter *frame
  157. );
  158. static unsigned evaluate_constant_subframe_(
  159. FLAC__StreamEncoder *encoder,
  160. const FLAC__int32 signal,
  161. unsigned blocksize,
  162. unsigned subframe_bps,
  163. FLAC__Subframe *subframe
  164. );
  165. static unsigned evaluate_fixed_subframe_(
  166. FLAC__StreamEncoder *encoder,
  167. const FLAC__int32 signal[],
  168. FLAC__int32 residual[],
  169. FLAC__uint64 abs_residual_partition_sums[],
  170. unsigned raw_bits_per_partition[],
  171. unsigned blocksize,
  172. unsigned subframe_bps,
  173. unsigned order,
  174. unsigned rice_parameter,
  175. unsigned rice_parameter_limit,
  176. unsigned min_partition_order,
  177. unsigned max_partition_order,
  178. FLAC__bool do_escape_coding,
  179. unsigned rice_parameter_search_dist,
  180. FLAC__Subframe *subframe,
  181. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  182. );
  183. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  184. static unsigned evaluate_lpc_subframe_(
  185. FLAC__StreamEncoder *encoder,
  186. const FLAC__int32 signal[],
  187. FLAC__int32 residual[],
  188. FLAC__uint64 abs_residual_partition_sums[],
  189. unsigned raw_bits_per_partition[],
  190. const FLAC__real lp_coeff[],
  191. unsigned blocksize,
  192. unsigned subframe_bps,
  193. unsigned order,
  194. unsigned qlp_coeff_precision,
  195. unsigned rice_parameter,
  196. unsigned rice_parameter_limit,
  197. unsigned min_partition_order,
  198. unsigned max_partition_order,
  199. FLAC__bool do_escape_coding,
  200. unsigned rice_parameter_search_dist,
  201. FLAC__Subframe *subframe,
  202. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  203. );
  204. #endif
  205. static unsigned evaluate_verbatim_subframe_(
  206. FLAC__StreamEncoder *encoder,
  207. const FLAC__int32 signal[],
  208. unsigned blocksize,
  209. unsigned subframe_bps,
  210. FLAC__Subframe *subframe
  211. );
  212. static unsigned find_best_partition_order_(
  213. struct FLAC__StreamEncoderPrivate *private_,
  214. const FLAC__int32 residual[],
  215. FLAC__uint64 abs_residual_partition_sums[],
  216. unsigned raw_bits_per_partition[],
  217. unsigned residual_samples,
  218. unsigned predictor_order,
  219. unsigned rice_parameter,
  220. unsigned rice_parameter_limit,
  221. unsigned min_partition_order,
  222. unsigned max_partition_order,
  223. unsigned bps,
  224. FLAC__bool do_escape_coding,
  225. unsigned rice_parameter_search_dist,
  226. FLAC__EntropyCodingMethod *best_ecm
  227. );
  228. static void precompute_partition_info_sums_(
  229. const FLAC__int32 residual[],
  230. FLAC__uint64 abs_residual_partition_sums[],
  231. unsigned residual_samples,
  232. unsigned predictor_order,
  233. unsigned min_partition_order,
  234. unsigned max_partition_order,
  235. unsigned bps
  236. );
  237. static void precompute_partition_info_escapes_(
  238. const FLAC__int32 residual[],
  239. unsigned raw_bits_per_partition[],
  240. unsigned residual_samples,
  241. unsigned predictor_order,
  242. unsigned min_partition_order,
  243. unsigned max_partition_order
  244. );
  245. static FLAC__bool set_partitioned_rice_(
  246. #ifdef EXACT_RICE_BITS_CALCULATION
  247. const FLAC__int32 residual[],
  248. #endif
  249. const FLAC__uint64 abs_residual_partition_sums[],
  250. const unsigned raw_bits_per_partition[],
  251. const unsigned residual_samples,
  252. const unsigned predictor_order,
  253. const unsigned suggested_rice_parameter,
  254. const unsigned rice_parameter_limit,
  255. const unsigned rice_parameter_search_dist,
  256. const unsigned partition_order,
  257. const FLAC__bool search_for_escapes,
  258. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  259. unsigned *bits
  260. );
  261. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  262. /* verify-related routines: */
  263. static void append_to_verify_fifo_(
  264. verify_input_fifo *fifo,
  265. const FLAC__int32 * const input[],
  266. unsigned input_offset,
  267. unsigned channels,
  268. unsigned wide_samples
  269. );
  270. static void append_to_verify_fifo_interleaved_(
  271. verify_input_fifo *fifo,
  272. const FLAC__int32 input[],
  273. unsigned input_offset,
  274. unsigned channels,
  275. unsigned wide_samples
  276. );
  277. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  278. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  279. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  280. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  281. static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  282. static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  283. static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  284. static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  285. static FILE *get_binary_stdout_(void);
  286. /***********************************************************************
  287. *
  288. * Private class data
  289. *
  290. ***********************************************************************/
  291. typedef struct FLAC__StreamEncoderPrivate {
  292. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  293. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  294. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  295. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  296. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  297. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  298. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  299. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  300. #endif
  301. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  302. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  303. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  304. FLAC__int32 *residual_workspace_mid_side[2][2];
  305. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  306. FLAC__Subframe subframe_workspace_mid_side[2][2];
  307. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  308. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  309. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  310. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  311. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  312. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  313. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  314. unsigned best_subframe_mid_side[2];
  315. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  316. unsigned best_subframe_bits_mid_side[2];
  317. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  318. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  319. FLAC__BitWriter *frame; /* the current frame being worked on */
  320. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  321. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  322. FLAC__ChannelAssignment last_channel_assignment;
  323. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  324. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  325. unsigned current_sample_number;
  326. unsigned current_frame_number;
  327. FLAC__MD5Context md5context;
  328. FLAC__CPUInfo cpuinfo;
  329. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  330. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  331. #else
  332. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  333. #endif
  334. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  335. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  336. void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  337. void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  338. void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  339. #endif
  340. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  341. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  342. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  343. FLAC__bool disable_constant_subframes;
  344. FLAC__bool disable_fixed_subframes;
  345. FLAC__bool disable_verbatim_subframes;
  346. #if FLAC__HAS_OGG
  347. FLAC__bool is_ogg;
  348. #endif
  349. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  350. FLAC__StreamEncoderSeekCallback seek_callback;
  351. FLAC__StreamEncoderTellCallback tell_callback;
  352. FLAC__StreamEncoderWriteCallback write_callback;
  353. FLAC__StreamEncoderMetadataCallback metadata_callback;
  354. FLAC__StreamEncoderProgressCallback progress_callback;
  355. void *client_data;
  356. unsigned first_seekpoint_to_check;
  357. FILE *file; /* only used when encoding to a file */
  358. FLAC__uint64 bytes_written;
  359. FLAC__uint64 samples_written;
  360. unsigned frames_written;
  361. unsigned total_frames_estimate;
  362. /* unaligned (original) pointers to allocated data */
  363. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  364. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  365. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  366. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  367. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  368. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  369. FLAC__real *windowed_signal_unaligned;
  370. #endif
  371. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  372. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  373. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  374. unsigned *raw_bits_per_partition_unaligned;
  375. /*
  376. * These fields have been moved here from private function local
  377. * declarations merely to save stack space during encoding.
  378. */
  379. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  380. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  381. #endif
  382. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  383. /*
  384. * The data for the verify section
  385. */
  386. struct {
  387. FLAC__StreamDecoder *decoder;
  388. EncoderStateHint state_hint;
  389. FLAC__bool needs_magic_hack;
  390. verify_input_fifo input_fifo;
  391. verify_output output;
  392. struct {
  393. FLAC__uint64 absolute_sample;
  394. unsigned frame_number;
  395. unsigned channel;
  396. unsigned sample;
  397. FLAC__int32 expected;
  398. FLAC__int32 got;
  399. } error_stats;
  400. } verify;
  401. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  402. } FLAC__StreamEncoderPrivate;
  403. /***********************************************************************
  404. *
  405. * Public static class data
  406. *
  407. ***********************************************************************/
  408. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  409. "FLAC__STREAM_ENCODER_OK",
  410. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  411. "FLAC__STREAM_ENCODER_OGG_ERROR",
  412. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  413. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  414. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  415. "FLAC__STREAM_ENCODER_IO_ERROR",
  416. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  417. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  418. };
  419. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  420. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  421. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  422. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  423. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  424. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  425. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  426. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  427. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  428. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  429. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  430. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  431. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  432. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  433. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  434. };
  435. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  436. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  437. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  438. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  439. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  440. };
  441. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  442. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  443. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  444. };
  445. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  446. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  447. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  448. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  449. };
  450. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  451. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  452. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  453. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  454. };
  455. /* Number of samples that will be overread to watch for end of stream. By
  456. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  457. * always try to read blocksize+1 samples before encoding a block, so that
  458. * even if the stream has a total sample count that is an integral multiple
  459. * of the blocksize, we will still notice when we are encoding the last
  460. * block. This is needed, for example, to correctly set the end-of-stream
  461. * marker in Ogg FLAC.
  462. *
  463. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  464. * not really any reason to change it.
  465. */
  466. static const unsigned OVERREAD_ = 1;
  467. /***********************************************************************
  468. *
  469. * Class constructor/destructor
  470. *
  471. */
  472. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  473. {
  474. FLAC__StreamEncoder *encoder;
  475. unsigned i;
  476. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  477. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  478. if(encoder == 0) {
  479. return 0;
  480. }
  481. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  482. if(encoder->protected_ == 0) {
  483. free(encoder);
  484. return 0;
  485. }
  486. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  487. if(encoder->private_ == 0) {
  488. free(encoder->protected_);
  489. free(encoder);
  490. return 0;
  491. }
  492. encoder->private_->frame = FLAC__bitwriter_new();
  493. if(encoder->private_->frame == 0) {
  494. free(encoder->private_);
  495. free(encoder->protected_);
  496. free(encoder);
  497. return 0;
  498. }
  499. encoder->private_->file = 0;
  500. set_defaults_(encoder);
  501. encoder->private_->is_being_deleted = false;
  502. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  503. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  504. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  505. }
  506. for(i = 0; i < 2; i++) {
  507. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  508. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  509. }
  510. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  511. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  512. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  513. }
  514. for(i = 0; i < 2; i++) {
  515. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  516. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  517. }
  518. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  519. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  520. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  521. }
  522. for(i = 0; i < 2; i++) {
  523. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  524. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  525. }
  526. for(i = 0; i < 2; i++)
  527. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  528. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  529. return encoder;
  530. }
  531. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  532. {
  533. unsigned i;
  534. FLAC__ASSERT(0 != encoder);
  535. FLAC__ASSERT(0 != encoder->protected_);
  536. FLAC__ASSERT(0 != encoder->private_);
  537. FLAC__ASSERT(0 != encoder->private_->frame);
  538. encoder->private_->is_being_deleted = true;
  539. (void)FLAC__stream_encoder_finish(encoder);
  540. if(0 != encoder->private_->verify.decoder)
  541. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  542. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  543. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  544. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  545. }
  546. for(i = 0; i < 2; i++) {
  547. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  548. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  549. }
  550. for(i = 0; i < 2; i++)
  551. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  552. FLAC__bitwriter_delete(encoder->private_->frame);
  553. free(encoder->private_);
  554. free(encoder->protected_);
  555. free(encoder);
  556. }
  557. /***********************************************************************
  558. *
  559. * Public class methods
  560. *
  561. ***********************************************************************/
  562. static FLAC__StreamEncoderInitStatus init_stream_internal_(
  563. FLAC__StreamEncoder *encoder,
  564. FLAC__StreamEncoderReadCallback read_callback,
  565. FLAC__StreamEncoderWriteCallback write_callback,
  566. FLAC__StreamEncoderSeekCallback seek_callback,
  567. FLAC__StreamEncoderTellCallback tell_callback,
  568. FLAC__StreamEncoderMetadataCallback metadata_callback,
  569. void *client_data,
  570. FLAC__bool is_ogg
  571. )
  572. {
  573. unsigned i;
  574. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  575. FLAC__ASSERT(0 != encoder);
  576. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  577. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  578. #if !FLAC__HAS_OGG
  579. if(is_ogg)
  580. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  581. #endif
  582. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  583. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  584. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  585. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  586. if(encoder->protected_->channels != 2) {
  587. encoder->protected_->do_mid_side_stereo = false;
  588. encoder->protected_->loose_mid_side_stereo = false;
  589. }
  590. else if(!encoder->protected_->do_mid_side_stereo)
  591. encoder->protected_->loose_mid_side_stereo = false;
  592. if(encoder->protected_->bits_per_sample >= 32)
  593. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  594. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  595. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  596. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  597. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  598. if(encoder->protected_->blocksize == 0) {
  599. if(encoder->protected_->max_lpc_order == 0)
  600. encoder->protected_->blocksize = 1152;
  601. else
  602. encoder->protected_->blocksize = 4096;
  603. }
  604. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  605. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  606. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  607. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  608. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  609. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  610. if(encoder->protected_->qlp_coeff_precision == 0) {
  611. if(encoder->protected_->bits_per_sample < 16) {
  612. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  613. /* @@@ until then we'll make a guess */
  614. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  615. }
  616. else if(encoder->protected_->bits_per_sample == 16) {
  617. if(encoder->protected_->blocksize <= 192)
  618. encoder->protected_->qlp_coeff_precision = 7;
  619. else if(encoder->protected_->blocksize <= 384)
  620. encoder->protected_->qlp_coeff_precision = 8;
  621. else if(encoder->protected_->blocksize <= 576)
  622. encoder->protected_->qlp_coeff_precision = 9;
  623. else if(encoder->protected_->blocksize <= 1152)
  624. encoder->protected_->qlp_coeff_precision = 10;
  625. else if(encoder->protected_->blocksize <= 2304)
  626. encoder->protected_->qlp_coeff_precision = 11;
  627. else if(encoder->protected_->blocksize <= 4608)
  628. encoder->protected_->qlp_coeff_precision = 12;
  629. else
  630. encoder->protected_->qlp_coeff_precision = 13;
  631. }
  632. else {
  633. if(encoder->protected_->blocksize <= 384)
  634. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  635. else if(encoder->protected_->blocksize <= 1152)
  636. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  637. else
  638. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  639. }
  640. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  641. }
  642. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  643. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  644. if(encoder->protected_->streamable_subset) {
  645. if(
  646. encoder->protected_->blocksize != 192 &&
  647. encoder->protected_->blocksize != 576 &&
  648. encoder->protected_->blocksize != 1152 &&
  649. encoder->protected_->blocksize != 2304 &&
  650. encoder->protected_->blocksize != 4608 &&
  651. encoder->protected_->blocksize != 256 &&
  652. encoder->protected_->blocksize != 512 &&
  653. encoder->protected_->blocksize != 1024 &&
  654. encoder->protected_->blocksize != 2048 &&
  655. encoder->protected_->blocksize != 4096 &&
  656. encoder->protected_->blocksize != 8192 &&
  657. encoder->protected_->blocksize != 16384
  658. )
  659. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  660. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  661. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  662. if(
  663. encoder->protected_->bits_per_sample != 8 &&
  664. encoder->protected_->bits_per_sample != 12 &&
  665. encoder->protected_->bits_per_sample != 16 &&
  666. encoder->protected_->bits_per_sample != 20 &&
  667. encoder->protected_->bits_per_sample != 24
  668. )
  669. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  670. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  671. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  672. if(
  673. encoder->protected_->sample_rate <= 48000 &&
  674. (
  675. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  676. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  677. )
  678. ) {
  679. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  680. }
  681. }
  682. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  683. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  684. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  685. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  686. #if FLAC__HAS_OGG
  687. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  688. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  689. unsigned i;
  690. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  691. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  692. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  693. for( ; i > 0; i--)
  694. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  695. encoder->protected_->metadata[0] = vc;
  696. break;
  697. }
  698. }
  699. }
  700. #endif
  701. /* keep track of any SEEKTABLE block */
  702. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  703. unsigned i;
  704. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  705. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  706. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  707. break; /* take only the first one */
  708. }
  709. }
  710. }
  711. /* validate metadata */
  712. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  713. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  714. metadata_has_seektable = false;
  715. metadata_has_vorbis_comment = false;
  716. metadata_picture_has_type1 = false;
  717. metadata_picture_has_type2 = false;
  718. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  719. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  720. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  721. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  722. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  723. if(metadata_has_seektable) /* only one is allowed */
  724. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  725. metadata_has_seektable = true;
  726. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  727. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  728. }
  729. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  730. if(metadata_has_vorbis_comment) /* only one is allowed */
  731. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  732. metadata_has_vorbis_comment = true;
  733. }
  734. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  735. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  736. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  737. }
  738. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  739. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  740. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  741. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  742. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  743. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  744. metadata_picture_has_type1 = true;
  745. /* standard icon must be 32x32 pixel PNG */
  746. if(
  747. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  748. (
  749. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  750. m->data.picture.width != 32 ||
  751. m->data.picture.height != 32
  752. )
  753. )
  754. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  755. }
  756. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  757. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  758. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  759. metadata_picture_has_type2 = true;
  760. }
  761. }
  762. }
  763. encoder->private_->input_capacity = 0;
  764. for(i = 0; i < encoder->protected_->channels; i++) {
  765. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  766. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  767. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  768. #endif
  769. }
  770. for(i = 0; i < 2; i++) {
  771. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  772. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  773. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  774. #endif
  775. }
  776. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  777. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  778. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  779. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  780. #endif
  781. for(i = 0; i < encoder->protected_->channels; i++) {
  782. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  783. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  784. encoder->private_->best_subframe[i] = 0;
  785. }
  786. for(i = 0; i < 2; i++) {
  787. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  788. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  789. encoder->private_->best_subframe_mid_side[i] = 0;
  790. }
  791. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  792. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  793. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  794. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  795. #else
  796. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  797. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  798. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  799. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  800. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  801. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  802. encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
  803. #endif
  804. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  805. encoder->private_->loose_mid_side_stereo_frames = 1;
  806. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  807. encoder->private_->current_sample_number = 0;
  808. encoder->private_->current_frame_number = 0;
  809. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  810. encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
  811. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  812. /*
  813. * get the CPU info and set the function pointers
  814. */
  815. FLAC__cpu_info(&encoder->private_->cpuinfo);
  816. /* first default to the non-asm routines */
  817. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  818. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  819. #endif
  820. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  821. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  822. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  823. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  824. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  825. #endif
  826. /* now override with asm where appropriate */
  827. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  828. # ifndef FLAC__NO_ASM
  829. if(encoder->private_->cpuinfo.use_asm) {
  830. # ifdef FLAC__CPU_IA32
  831. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  832. # ifdef FLAC__HAS_NASM
  833. if(encoder->private_->cpuinfo.data.ia32.sse) {
  834. if(encoder->protected_->max_lpc_order < 4)
  835. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  836. else if(encoder->protected_->max_lpc_order < 8)
  837. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  838. else if(encoder->protected_->max_lpc_order < 12)
  839. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  840. else
  841. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  842. }
  843. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  844. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  845. else
  846. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  847. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  848. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  849. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  850. }
  851. else {
  852. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  853. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  854. }
  855. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  856. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  857. # endif /* FLAC__HAS_NASM */
  858. # endif /* FLAC__CPU_IA32 */
  859. }
  860. # endif /* !FLAC__NO_ASM */
  861. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  862. /* finally override based on wide-ness if necessary */
  863. if(encoder->private_->use_wide_by_block) {
  864. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  865. }
  866. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  867. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  868. #if FLAC__HAS_OGG
  869. encoder->private_->is_ogg = is_ogg;
  870. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  871. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  872. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  873. }
  874. #endif
  875. encoder->private_->read_callback = read_callback;
  876. encoder->private_->write_callback = write_callback;
  877. encoder->private_->seek_callback = seek_callback;
  878. encoder->private_->tell_callback = tell_callback;
  879. encoder->private_->metadata_callback = metadata_callback;
  880. encoder->private_->client_data = client_data;
  881. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  882. /* the above function sets the state for us in case of an error */
  883. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  884. }
  885. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  886. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  887. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  888. }
  889. /*
  890. * Set up the verify stuff if necessary
  891. */
  892. if(encoder->protected_->verify) {
  893. /*
  894. * First, set up the fifo which will hold the
  895. * original signal to compare against
  896. */
  897. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  898. for(i = 0; i < encoder->protected_->channels; i++) {
  899. if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)safe_malloc_mul_2op_(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
  900. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  901. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  902. }
  903. }
  904. encoder->private_->verify.input_fifo.tail = 0;
  905. /*
  906. * Now set up a stream decoder for verification
  907. */
  908. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  909. if(0 == encoder->private_->verify.decoder) {
  910. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  911. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  912. }
  913. if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
  914. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  915. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  916. }
  917. }
  918. encoder->private_->verify.error_stats.absolute_sample = 0;
  919. encoder->private_->verify.error_stats.frame_number = 0;
  920. encoder->private_->verify.error_stats.channel = 0;
  921. encoder->private_->verify.error_stats.sample = 0;
  922. encoder->private_->verify.error_stats.expected = 0;
  923. encoder->private_->verify.error_stats.got = 0;
  924. /*
  925. * These must be done before we write any metadata, because that
  926. * calls the write_callback, which uses these values.
  927. */
  928. encoder->private_->first_seekpoint_to_check = 0;
  929. encoder->private_->samples_written = 0;
  930. encoder->protected_->streaminfo_offset = 0;
  931. encoder->protected_->seektable_offset = 0;
  932. encoder->protected_->audio_offset = 0;
  933. /*
  934. * write the stream header
  935. */
  936. if(encoder->protected_->verify)
  937. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  938. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  939. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  940. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  941. }
  942. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  943. /* the above function sets the state for us in case of an error */
  944. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  945. }
  946. /*
  947. * write the STREAMINFO metadata block
  948. */
  949. if(encoder->protected_->verify)
  950. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  951. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  952. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  953. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  954. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  955. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  956. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  957. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  958. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  959. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  960. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  961. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  962. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  963. if(encoder->protected_->do_md5)
  964. FLAC__MD5Init(&encoder->private_->md5context);
  965. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  966. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  967. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  968. }
  969. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  970. /* the above function sets the state for us in case of an error */
  971. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  972. }
  973. /*
  974. * Now that the STREAMINFO block is written, we can init this to an
  975. * absurdly-high value...
  976. */
  977. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  978. /* ... and clear this to 0 */
  979. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  980. /*
  981. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  982. * if not, we will write an empty one (FLAC__add_metadata_block()
  983. * automatically supplies the vendor string).
  984. *
  985. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  986. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  987. * true it will have already insured that the metadata list is properly
  988. * ordered.)
  989. */
  990. if(!metadata_has_vorbis_comment) {
  991. FLAC__StreamMetadata vorbis_comment;
  992. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  993. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  994. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  995. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  996. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  997. vorbis_comment.data.vorbis_comment.num_comments = 0;
  998. vorbis_comment.data.vorbis_comment.comments = 0;
  999. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  1000. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  1001. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  1002. }
  1003. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  1004. /* the above function sets the state for us in case of an error */
  1005. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  1006. }
  1007. }
  1008. /*
  1009. * write the user's metadata blocks
  1010. */
  1011. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  1012. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  1013. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  1014. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  1015. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  1016. }
  1017. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  1018. /* the above function sets the state for us in case of an error */
  1019. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  1020. }
  1021. }
  1022. /* now that all the metadata is written, we save the stream offset */
  1023. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  1024. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  1025. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  1026. }
  1027. if(encoder->protected_->verify)
  1028. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  1029. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  1030. }
  1031. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  1032. FLAC__StreamEncoder *encoder,
  1033. FLAC__StreamEncoderWriteCallback write_callback,
  1034. FLAC__StreamEncoderSeekCallback seek_callback,
  1035. FLAC__StreamEncoderTellCallback tell_callback,
  1036. FLAC__StreamEncoderMetadataCallback metadata_callback,
  1037. void *client_data
  1038. )
  1039. {
  1040. return init_stream_internal_(
  1041. encoder,
  1042. /*read_callback=*/0,
  1043. write_callback,
  1044. seek_callback,
  1045. tell_callback,
  1046. metadata_callback,
  1047. client_data,
  1048. /*is_ogg=*/false
  1049. );
  1050. }
  1051. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  1052. FLAC__StreamEncoder *encoder,
  1053. FLAC__StreamEncoderReadCallback read_callback,
  1054. FLAC__StreamEncoderWriteCallback write_callback,
  1055. FLAC__StreamEncoderSeekCallback seek_callback,
  1056. FLAC__StreamEncoderTellCallback tell_callback,
  1057. FLAC__StreamEncoderMetadataCallback metadata_callback,
  1058. void *client_data
  1059. )
  1060. {
  1061. return init_stream_internal_(
  1062. encoder,
  1063. read_callback,
  1064. write_callback,
  1065. seek_callback,
  1066. tell_callback,
  1067. metadata_callback,
  1068. client_data,
  1069. /*is_ogg=*/true
  1070. );
  1071. }
  1072. static FLAC__StreamEncoderInitStatus init_FILE_internal_(
  1073. FLAC__StreamEncoder *encoder,
  1074. FILE *file,
  1075. FLAC__StreamEncoderProgressCallback progress_callback,
  1076. void *client_data,
  1077. FLAC__bool is_ogg
  1078. )
  1079. {
  1080. FLAC__StreamEncoderInitStatus init_status;
  1081. FLAC__ASSERT(0 != encoder);
  1082. FLAC__ASSERT(0 != file);
  1083. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1084. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  1085. /* double protection */
  1086. if(file == 0) {
  1087. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  1088. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  1089. }
  1090. /*
  1091. * To make sure that our file does not go unclosed after an error, we
  1092. * must assign the FILE pointer before any further error can occur in
  1093. * this routine.
  1094. */
  1095. if(file == stdout)
  1096. file = get_binary_stdout_(); /* just to be safe */
  1097. encoder->private_->file = file;
  1098. encoder->private_->progress_callback = progress_callback;
  1099. encoder->private_->bytes_written = 0;
  1100. encoder->private_->samples_written = 0;
  1101. encoder->private_->frames_written = 0;
  1102. init_status = init_stream_internal_(
  1103. encoder,
  1104. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
  1105. file_write_callback_,
  1106. encoder->private_->file == stdout? 0 : file_seek_callback_,
  1107. encoder->private_->file == stdout? 0 : file_tell_callback_,
  1108. /*metadata_callback=*/0,
  1109. client_data,
  1110. is_ogg
  1111. );
  1112. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  1113. /* the above function sets the state for us in case of an error */
  1114. return init_status;
  1115. }
  1116. {
  1117. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  1118. FLAC__ASSERT(blocksize != 0);
  1119. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  1120. }
  1121. return init_status;
  1122. }
  1123. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  1124. FLAC__StreamEncoder *encoder,
  1125. FILE *file,
  1126. FLAC__StreamEncoderProgressCallback progress_callback,
  1127. void *client_data
  1128. )
  1129. {
  1130. return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  1131. }
  1132. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  1133. FLAC__StreamEncoder *encoder,
  1134. FILE *file,
  1135. FLAC__StreamEncoderProgressCallback progress_callback,
  1136. void *client_data
  1137. )
  1138. {
  1139. return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  1140. }
  1141. static FLAC__StreamEncoderInitStatus init_file_internal_(
  1142. FLAC__StreamEncoder *encoder,
  1143. const char *filename,
  1144. FLAC__StreamEncoderProgressCallback progress_callback,
  1145. void *client_data,
  1146. FLAC__bool is_ogg
  1147. )
  1148. {
  1149. FILE *file;
  1150. FLAC__ASSERT(0 != encoder);
  1151. /*
  1152. * To make sure that our file does not go unclosed after an error, we
  1153. * have to do the same entrance checks here that are later performed
  1154. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  1155. */
  1156. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1157. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  1158. file = filename? fopen(filename, "w+b") : stdout;
  1159. if(file == 0) {
  1160. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  1161. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  1162. }
  1163. return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
  1164. }
  1165. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  1166. FLAC__StreamEncoder *encoder,
  1167. const char *filename,
  1168. FLAC__StreamEncoderProgressCallback progress_callback,
  1169. void *client_data
  1170. )
  1171. {
  1172. return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  1173. }
  1174. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  1175. FLAC__StreamEncoder *encoder,
  1176. const char *filename,
  1177. FLAC__StreamEncoderProgressCallback progress_callback,
  1178. void *client_data
  1179. )
  1180. {
  1181. return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  1182. }
  1183. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  1184. {
  1185. FLAC__bool error = false;
  1186. FLAC__ASSERT(0 != encoder);
  1187. FLAC__ASSERT(0 != encoder->private_);
  1188. FLAC__ASSERT(0 != encoder->protected_);
  1189. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  1190. return true;
  1191. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  1192. if(encoder->private_->current_sample_number != 0) {
  1193. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  1194. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  1195. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  1196. error = true;
  1197. }
  1198. }
  1199. if(encoder->protected_->do_md5)
  1200. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  1201. if(!encoder->private_->is_being_deleted) {
  1202. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  1203. if(encoder->private_->seek_callback) {
  1204. #if FLAC__HAS_OGG
  1205. if(encoder->private_->is_ogg)
  1206. update_ogg_metadata_(encoder);
  1207. else
  1208. #endif
  1209. update_metadata_(encoder);
  1210. /* check if an error occurred while updating metadata */
  1211. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  1212. error = true;
  1213. }
  1214. if(encoder->private_->metadata_callback)
  1215. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  1216. }
  1217. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  1218. if(!error)
  1219. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  1220. error = true;
  1221. }
  1222. }
  1223. if(0 != encoder->private_->file) {
  1224. if(encoder->private_->file != stdout)
  1225. fclose(encoder->private_->file);
  1226. encoder->private_->file = 0;
  1227. }
  1228. #if FLAC__HAS_OGG
  1229. if(encoder->private_->is_ogg)
  1230. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  1231. #endif
  1232. free_(encoder);
  1233. set_defaults_(encoder);
  1234. if(!error)
  1235. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  1236. return !error;
  1237. }
  1238. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  1239. {
  1240. FLAC__ASSERT(0 != encoder);
  1241. FLAC__ASSERT(0 != encoder->private_);
  1242. FLAC__ASSERT(0 != encoder->protected_);
  1243. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1244. return false;
  1245. #if FLAC__HAS_OGG
  1246. /* can't check encoder->private_->is_ogg since that's not set until init time */
  1247. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  1248. return true;
  1249. #else
  1250. (void)value;
  1251. return false;
  1252. #endif
  1253. }
  1254. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  1255. {
  1256. FLAC__ASSERT(0 != encoder);
  1257. FLAC__ASSERT(0 != encoder->private_);
  1258. FLAC__ASSERT(0 != encoder->protected_);
  1259. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1260. return false;
  1261. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  1262. encoder->protected_->verify = value;
  1263. #endif
  1264. return true;
  1265. }
  1266. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  1267. {
  1268. FLAC__ASSERT(0 != encoder);
  1269. FLAC__ASSERT(0 != encoder->private_);
  1270. FLAC__ASSERT(0 != encoder->protected_);
  1271. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1272. return false;
  1273. encoder->protected_->streamable_subset = value;
  1274. return true;
  1275. }
  1276. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  1277. {
  1278. FLAC__ASSERT(0 != encoder);
  1279. FLAC__ASSERT(0 != encoder->private_);
  1280. FLAC__ASSERT(0 != encoder->protected_);
  1281. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1282. return false;
  1283. encoder->protected_->channels = value;
  1284. return true;
  1285. }
  1286. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  1287. {
  1288. FLAC__ASSERT(0 != encoder);
  1289. FLAC__ASSERT(0 != encoder->private_);
  1290. FLAC__ASSERT(0 != encoder->protected_);
  1291. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1292. return false;
  1293. encoder->protected_->bits_per_sample = value;
  1294. return true;
  1295. }
  1296. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  1297. {
  1298. FLAC__ASSERT(0 != encoder);
  1299. FLAC__ASSERT(0 != encoder->private_);
  1300. FLAC__ASSERT(0 != encoder->protected_);
  1301. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1302. return false;
  1303. encoder->protected_->sample_rate = value;
  1304. return true;
  1305. }
  1306. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  1307. {
  1308. FLAC__bool ok = true;
  1309. FLAC__ASSERT(0 != encoder);
  1310. FLAC__ASSERT(0 != encoder->private_);
  1311. FLAC__ASSERT(0 != encoder->protected_);
  1312. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1313. return false;
  1314. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  1315. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  1316. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  1317. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  1318. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  1319. #if 0
  1320. /* was: */
  1321. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  1322. /* but it's too hard to specify the string in a locale-specific way */
  1323. #else
  1324. encoder->protected_->num_apodizations = 1;
  1325. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  1326. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  1327. #endif
  1328. #endif
  1329. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  1330. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  1331. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  1332. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  1333. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  1334. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  1335. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  1336. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  1337. return ok;
  1338. }
  1339. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  1340. {
  1341. FLAC__ASSERT(0 != encoder);
  1342. FLAC__ASSERT(0 != encoder->private_);
  1343. FLAC__ASSERT(0 != encoder->protected_);
  1344. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1345. return false;
  1346. encoder->protected_->blocksize = value;
  1347. return true;
  1348. }
  1349. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  1350. {
  1351. FLAC__ASSERT(0 != encoder);
  1352. FLAC__ASSERT(0 != encoder->private_);
  1353. FLAC__ASSERT(0 != encoder->protected_);
  1354. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1355. return false;
  1356. encoder->protected_->do_mid_side_stereo = value;
  1357. return true;
  1358. }
  1359. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  1360. {
  1361. FLAC__ASSERT(0 != encoder);
  1362. FLAC__ASSERT(0 != encoder->private_);
  1363. FLAC__ASSERT(0 != encoder->protected_);
  1364. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1365. return false;
  1366. encoder->protected_->loose_mid_side_stereo = value;
  1367. return true;
  1368. }
  1369. /*@@@@add to tests*/
  1370. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  1371. {
  1372. FLAC__ASSERT(0 != encoder);
  1373. FLAC__ASSERT(0 != encoder->private_);
  1374. FLAC__ASSERT(0 != encoder->protected_);
  1375. FLAC__ASSERT(0 != specification);
  1376. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1377. return false;
  1378. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  1379. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  1380. #else
  1381. encoder->protected_->num_apodizations = 0;
  1382. while(1) {
  1383. const char *s = strchr(specification, ';');
  1384. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  1385. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  1386. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  1387. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  1388. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  1389. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  1390. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  1391. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  1392. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  1393. else if(n==6 && 0 == strncmp("connes" , specification, n))
  1394. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  1395. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  1396. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  1397. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  1398. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  1399. if (stddev > 0.0 && stddev <= 0.5) {
  1400. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  1401. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  1402. }
  1403. }
  1404. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  1405. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  1406. else if(n==4 && 0 == strncmp("hann" , specification, n))
  1407. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  1408. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  1409. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  1410. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  1411. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  1412. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  1413. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  1414. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  1415. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  1416. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  1417. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  1418. if (p >= 0.0 && p <= 1.0) {
  1419. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  1420. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  1421. }
  1422. }
  1423. else if(n==5 && 0 == strncmp("welch" , specification, n))
  1424. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  1425. if (encoder->protected_->num_apodizations == 32)
  1426. break;
  1427. if (s)
  1428. specification = s+1;
  1429. else
  1430. break;
  1431. }
  1432. if(encoder->protected_->num_apodizations == 0) {
  1433. encoder->protected_->num_apodizations = 1;
  1434. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  1435. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  1436. }
  1437. #endif
  1438. return true;
  1439. }
  1440. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  1441. {
  1442. FLAC__ASSERT(0 != encoder);
  1443. FLAC__ASSERT(0 != encoder->private_);
  1444. FLAC__ASSERT(0 != encoder->protected_);
  1445. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1446. return false;
  1447. encoder->protected_->max_lpc_order = value;
  1448. return true;
  1449. }
  1450. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  1451. {
  1452. FLAC__ASSERT(0 != encoder);
  1453. FLAC__ASSERT(0 != encoder->private_);
  1454. FLAC__ASSERT(0 != encoder->protected_);
  1455. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1456. return false;
  1457. encoder->protected_->qlp_coeff_precision = value;
  1458. return true;
  1459. }
  1460. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  1461. {
  1462. FLAC__ASSERT(0 != encoder);
  1463. FLAC__ASSERT(0 != encoder->private_);
  1464. FLAC__ASSERT(0 != encoder->protected_);
  1465. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1466. return false;
  1467. encoder->protected_->do_qlp_coeff_prec_search = value;
  1468. return true;
  1469. }
  1470. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  1471. {
  1472. FLAC__ASSERT(0 != encoder);
  1473. FLAC__ASSERT(0 != encoder->private_);
  1474. FLAC__ASSERT(0 != encoder->protected_);
  1475. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1476. return false;
  1477. #if 0
  1478. /*@@@ deprecated: */
  1479. encoder->protected_->do_escape_coding = value;
  1480. #else
  1481. (void)value;
  1482. #endif
  1483. return true;
  1484. }
  1485. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  1486. {
  1487. FLAC__ASSERT(0 != encoder);
  1488. FLAC__ASSERT(0 != encoder->private_);
  1489. FLAC__ASSERT(0 != encoder->protected_);
  1490. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1491. return false;
  1492. encoder->protected_->do_exhaustive_model_search = value;
  1493. return true;
  1494. }
  1495. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  1496. {
  1497. FLAC__ASSERT(0 != encoder);
  1498. FLAC__ASSERT(0 != encoder->private_);
  1499. FLAC__ASSERT(0 != encoder->protected_);
  1500. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1501. return false;
  1502. encoder->protected_->min_residual_partition_order = value;
  1503. return true;
  1504. }
  1505. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  1506. {
  1507. FLAC__ASSERT(0 != encoder);
  1508. FLAC__ASSERT(0 != encoder->private_);
  1509. FLAC__ASSERT(0 != encoder->protected_);
  1510. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1511. return false;
  1512. encoder->protected_->max_residual_partition_order = value;
  1513. return true;
  1514. }
  1515. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  1516. {
  1517. FLAC__ASSERT(0 != encoder);
  1518. FLAC__ASSERT(0 != encoder->private_);
  1519. FLAC__ASSERT(0 != encoder->protected_);
  1520. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1521. return false;
  1522. #if 0
  1523. /*@@@ deprecated: */
  1524. encoder->protected_->rice_parameter_search_dist = value;
  1525. #else
  1526. (void)value;
  1527. #endif
  1528. return true;
  1529. }
  1530. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  1531. {
  1532. FLAC__ASSERT(0 != encoder);
  1533. FLAC__ASSERT(0 != encoder->private_);
  1534. FLAC__ASSERT(0 != encoder->protected_);
  1535. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1536. return false;
  1537. encoder->protected_->total_samples_estimate = value;
  1538. return true;
  1539. }
  1540. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  1541. {
  1542. FLAC__ASSERT(0 != encoder);
  1543. FLAC__ASSERT(0 != encoder->private_);
  1544. FLAC__ASSERT(0 != encoder->protected_);
  1545. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  1546. return false;
  1547. if(0 == metadata)
  1548. num_blocks = 0;
  1549. if(0 == num_blocks)
  1550. metadata = 0;
  1551. /* realloc() does not do exactly what we want so... */
  1552. if(encoder->protected_->metadata) {
  1553. free(encoder->protected_->metadata);
  1554. encoder->protected_->metadata = 0;
  1555. encoder->protected_->num_metadata_blocks = 0;
  1556. }
  1557. if(num_blocks) {
  1558. FLAC__StreamMetadata **m;
  1559. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  1560. return false;
  1561. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  1562. encoder->protected_->metadata = m;
  1563. encoder->protected_->num_metadata_blocks = num_blocks;
  1564. }
  1565. #if FLAC__HAS_OGG
  1566. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  1567. return false;
  1568. #endif
  1569. return true;
  1570. }
  1571. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  1572. {
  1573. FLAC__ASSERT(0 != encoder);
  1574. FLAC__ASSERT(0 != encoder->private_);
  1575. FLAC__ASSERT(0 != encoder->protected_);
  1576. return encoder->protected_->state;
  1577. }
  1578. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  1579. {
  1580. FLAC__ASSERT(0 != encoder);
  1581. FLAC__ASSERT(0 != encoder->private_);
  1582. FLAC__ASSERT(0 != encoder->protected_);
  1583. if(encoder->protected_->verify)
  1584. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  1585. else
  1586. return FLAC__STREAM_DECODER_UNINITIALIZED;
  1587. }
  1588. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  1589. {
  1590. FLAC__ASSERT(0 != encoder);
  1591. FLAC__ASSERT(0 != encoder->private_);
  1592. FLAC__ASSERT(0 != encoder->protected_);
  1593. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  1594. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  1595. else
  1596. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  1597. }
  1598. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
  1599. {
  1600. FLAC__ASSERT(0 != encoder);
  1601. FLAC__ASSERT(0 != encoder->private_);
  1602. FLAC__ASSERT(0 != encoder->protected_);
  1603. if(0 != absolute_sample)
  1604. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  1605. if(0 != frame_number)
  1606. *frame_number = encoder->private_->verify.error_stats.frame_number;
  1607. if(0 != channel)
  1608. *channel = encoder->private_->verify.error_stats.channel;
  1609. if(0 != sample)
  1610. *sample = encoder->private_->verify.error_stats.sample;
  1611. if(0 != expected)
  1612. *expected = encoder->private_->verify.error_stats.expected;
  1613. if(0 != got)
  1614. *got = encoder->private_->verify.error_stats.got;
  1615. }
  1616. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  1617. {
  1618. FLAC__ASSERT(0 != encoder);
  1619. FLAC__ASSERT(0 != encoder->private_);
  1620. FLAC__ASSERT(0 != encoder->protected_);
  1621. return encoder->protected_->verify;
  1622. }
  1623. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  1624. {
  1625. FLAC__ASSERT(0 != encoder);
  1626. FLAC__ASSERT(0 != encoder->private_);
  1627. FLAC__ASSERT(0 != encoder->protected_);
  1628. return encoder->protected_->streamable_subset;
  1629. }
  1630. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  1631. {
  1632. FLAC__ASSERT(0 != encoder);
  1633. FLAC__ASSERT(0 != encoder->private_);
  1634. FLAC__ASSERT(0 != encoder->protected_);
  1635. return encoder->protected_->channels;
  1636. }
  1637. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  1638. {
  1639. FLAC__ASSERT(0 != encoder);
  1640. FLAC__ASSERT(0 != encoder->private_);
  1641. FLAC__ASSERT(0 != encoder->protected_);
  1642. return encoder->protected_->bits_per_sample;
  1643. }
  1644. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  1645. {
  1646. FLAC__ASSERT(0 != encoder);
  1647. FLAC__ASSERT(0 != encoder->private_);
  1648. FLAC__ASSERT(0 != encoder->protected_);
  1649. return encoder->protected_->sample_rate;
  1650. }
  1651. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  1652. {
  1653. FLAC__ASSERT(0 != encoder);
  1654. FLAC__ASSERT(0 != encoder->private_);
  1655. FLAC__ASSERT(0 != encoder->protected_);
  1656. return encoder->protected_->blocksize;
  1657. }
  1658. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  1659. {
  1660. FLAC__ASSERT(0 != encoder);
  1661. FLAC__ASSERT(0 != encoder->private_);
  1662. FLAC__ASSERT(0 != encoder->protected_);
  1663. return encoder->protected_->do_mid_side_stereo;
  1664. }
  1665. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  1666. {
  1667. FLAC__ASSERT(0 != encoder);
  1668. FLAC__ASSERT(0 != encoder->private_);
  1669. FLAC__ASSERT(0 != encoder->protected_);
  1670. return encoder->protected_->loose_mid_side_stereo;
  1671. }
  1672. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  1673. {
  1674. FLAC__ASSERT(0 != encoder);
  1675. FLAC__ASSERT(0 != encoder->private_);
  1676. FLAC__ASSERT(0 != encoder->protected_);
  1677. return encoder->protected_->max_lpc_order;
  1678. }
  1679. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  1680. {
  1681. FLAC__ASSERT(0 != encoder);
  1682. FLAC__ASSERT(0 != encoder->private_);
  1683. FLAC__ASSERT(0 != encoder->protected_);
  1684. return encoder->protected_->qlp_coeff_precision;
  1685. }
  1686. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  1687. {
  1688. FLAC__ASSERT(0 != encoder);
  1689. FLAC__ASSERT(0 != encoder->private_);
  1690. FLAC__ASSERT(0 != encoder->protected_);
  1691. return encoder->protected_->do_qlp_coeff_prec_search;
  1692. }
  1693. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  1694. {
  1695. FLAC__ASSERT(0 != encoder);
  1696. FLAC__ASSERT(0 != encoder->private_);
  1697. FLAC__ASSERT(0 != encoder->protected_);
  1698. return encoder->protected_->do_escape_coding;
  1699. }
  1700. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  1701. {
  1702. FLAC__ASSERT(0 != encoder);
  1703. FLAC__ASSERT(0 != encoder->private_);
  1704. FLAC__ASSERT(0 != encoder->protected_);
  1705. return encoder->protected_->do_exhaustive_model_search;
  1706. }
  1707. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  1708. {
  1709. FLAC__ASSERT(0 != encoder);
  1710. FLAC__ASSERT(0 != encoder->private_);
  1711. FLAC__ASSERT(0 != encoder->protected_);
  1712. return encoder->protected_->min_residual_partition_order;
  1713. }
  1714. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  1715. {
  1716. FLAC__ASSERT(0 != encoder);
  1717. FLAC__ASSERT(0 != encoder->private_);
  1718. FLAC__ASSERT(0 != encoder->protected_);
  1719. return encoder->protected_->max_residual_partition_order;
  1720. }
  1721. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  1722. {
  1723. FLAC__ASSERT(0 != encoder);
  1724. FLAC__ASSERT(0 != encoder->private_);
  1725. FLAC__ASSERT(0 != encoder->protected_);
  1726. return encoder->protected_->rice_parameter_search_dist;
  1727. }
  1728. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  1729. {
  1730. FLAC__ASSERT(0 != encoder);
  1731. FLAC__ASSERT(0 != encoder->private_);
  1732. FLAC__ASSERT(0 != encoder->protected_);
  1733. return encoder->protected_->total_samples_estimate;
  1734. }
  1735. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  1736. {
  1737. unsigned i, j = 0, channel;
  1738. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  1739. FLAC__ASSERT(0 != encoder);
  1740. FLAC__ASSERT(0 != encoder->private_);
  1741. FLAC__ASSERT(0 != encoder->protected_);
  1742. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  1743. do {
  1744. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  1745. if(encoder->protected_->verify)
  1746. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  1747. for(channel = 0; channel < channels; channel++)
  1748. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  1749. if(encoder->protected_->do_mid_side_stereo) {
  1750. FLAC__ASSERT(channels == 2);
  1751. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  1752. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  1753. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  1754. encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
  1755. }
  1756. }
  1757. else
  1758. j += n;
  1759. encoder->private_->current_sample_number += n;
  1760. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  1761. if(encoder->private_->current_sample_number > blocksize) {
  1762. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  1763. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  1764. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  1765. return false;
  1766. /* move unprocessed overread samples to beginnings of arrays */
  1767. for(channel = 0; channel < channels; channel++)
  1768. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  1769. if(encoder->protected_->do_mid_side_stereo) {
  1770. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  1771. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  1772. }
  1773. encoder->private_->current_sample_number = 1;
  1774. }
  1775. } while(j < samples);
  1776. return true;
  1777. }
  1778. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  1779. {
  1780. unsigned i, j, k, channel;
  1781. FLAC__int32 x, mid, side;
  1782. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  1783. FLAC__ASSERT(0 != encoder);
  1784. FLAC__ASSERT(0 != encoder->private_);
  1785. FLAC__ASSERT(0 != encoder->protected_);
  1786. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  1787. j = k = 0;
  1788. /*
  1789. * we have several flavors of the same basic loop, optimized for
  1790. * different conditions:
  1791. */
  1792. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  1793. /*
  1794. * stereo coding: unroll channel loop
  1795. */
  1796. do {
  1797. if(encoder->protected_->verify)
  1798. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  1799. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  1800. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  1801. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  1802. x = buffer[k++];
  1803. encoder->private_->integer_signal[1][i] = x;
  1804. mid += x;
  1805. side -= x;
  1806. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  1807. encoder->private_->integer_signal_mid_side[1][i] = side;
  1808. encoder->private_->integer_signal_mid_side[0][i] = mid;
  1809. }
  1810. encoder->private_->current_sample_number = i;
  1811. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  1812. if(i > blocksize) {
  1813. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  1814. return false;
  1815. /* move unprocessed overread samples to beginnings of arrays */
  1816. FLAC__ASSERT(i == blocksize+OVERREAD_);
  1817. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  1818. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  1819. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  1820. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  1821. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  1822. encoder->private_->current_sample_number = 1;
  1823. }
  1824. } while(j < samples);
  1825. }
  1826. else {
  1827. /*
  1828. * independent channel coding: buffer each channel in inner loop
  1829. */
  1830. do {
  1831. if(encoder->protected_->verify)
  1832. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  1833. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  1834. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  1835. for(channel = 0; channel < channels; channel++)
  1836. encoder->private_->integer_signal[channel][i] = buffer[k++];
  1837. }
  1838. encoder->private_->current_sample_number = i;
  1839. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  1840. if(i > blocksize) {
  1841. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  1842. return false;
  1843. /* move unprocessed overread samples to beginnings of arrays */
  1844. FLAC__ASSERT(i == blocksize+OVERREAD_);
  1845. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  1846. for(channel = 0; channel < channels; channel++)
  1847. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  1848. encoder->private_->current_sample_number = 1;
  1849. }
  1850. } while(j < samples);
  1851. }
  1852. return true;
  1853. }
  1854. /***********************************************************************
  1855. *
  1856. * Private class methods
  1857. *
  1858. ***********************************************************************/
  1859. void set_defaults_(FLAC__StreamEncoder *encoder)
  1860. {
  1861. FLAC__ASSERT(0 != encoder);
  1862. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  1863. encoder->protected_->verify = true;
  1864. #else
  1865. encoder->protected_->verify = false;
  1866. #endif
  1867. encoder->protected_->streamable_subset = true;
  1868. encoder->protected_->do_md5 = true;
  1869. encoder->protected_->do_mid_side_stereo = false;
  1870. encoder->protected_->loose_mid_side_stereo = false;
  1871. encoder->protected_->channels = 2;
  1872. encoder->protected_->bits_per_sample = 16;
  1873. encoder->protected_->sample_rate = 44100;
  1874. encoder->protected_->blocksize = 0;
  1875. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  1876. encoder->protected_->num_apodizations = 1;
  1877. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  1878. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  1879. #endif
  1880. encoder->protected_->max_lpc_order = 0;
  1881. encoder->protected_->qlp_coeff_precision = 0;
  1882. encoder->protected_->do_qlp_coeff_prec_search = false;
  1883. encoder->protected_->do_exhaustive_model_search = false;
  1884. encoder->protected_->do_escape_coding = false;
  1885. encoder->protected_->min_residual_partition_order = 0;
  1886. encoder->protected_->max_residual_partition_order = 0;
  1887. encoder->protected_->rice_parameter_search_dist = 0;
  1888. encoder->protected_->total_samples_estimate = 0;
  1889. encoder->protected_->metadata = 0;
  1890. encoder->protected_->num_metadata_blocks = 0;
  1891. encoder->private_->seek_table = 0;
  1892. encoder->private_->disable_constant_subframes = false;
  1893. encoder->private_->disable_fixed_subframes = false;
  1894. encoder->private_->disable_verbatim_subframes = false;
  1895. #if FLAC__HAS_OGG
  1896. encoder->private_->is_ogg = false;
  1897. #endif
  1898. encoder->private_->read_callback = 0;
  1899. encoder->private_->write_callback = 0;
  1900. encoder->private_->seek_callback = 0;
  1901. encoder->private_->tell_callback = 0;
  1902. encoder->private_->metadata_callback = 0;
  1903. encoder->private_->progress_callback = 0;
  1904. encoder->private_->client_data = 0;
  1905. #if FLAC__HAS_OGG
  1906. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  1907. #endif
  1908. }
  1909. void free_(FLAC__StreamEncoder *encoder)
  1910. {
  1911. unsigned i, channel;
  1912. FLAC__ASSERT(0 != encoder);
  1913. if(encoder->protected_->metadata) {
  1914. free(encoder->protected_->metadata);
  1915. encoder->protected_->metadata = 0;
  1916. encoder->protected_->num_metadata_blocks = 0;
  1917. }
  1918. for(i = 0; i < encoder->protected_->channels; i++) {
  1919. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  1920. free(encoder->private_->integer_signal_unaligned[i]);
  1921. encoder->private_->integer_signal_unaligned[i] = 0;
  1922. }
  1923. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  1924. if(0 != encoder->private_->real_signal_unaligned[i]) {
  1925. free(encoder->private_->real_signal_unaligned[i]);
  1926. encoder->private_->real_signal_unaligned[i] = 0;
  1927. }
  1928. #endif
  1929. }
  1930. for(i = 0; i < 2; i++) {
  1931. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  1932. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  1933. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  1934. }
  1935. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  1936. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  1937. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  1938. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  1939. }
  1940. #endif
  1941. }
  1942. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  1943. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  1944. if(0 != encoder->private_->window_unaligned[i]) {
  1945. free(encoder->private_->window_unaligned[i]);
  1946. encoder->private_->window_unaligned[i] = 0;
  1947. }
  1948. }
  1949. if(0 != encoder->private_->windowed_signal_unaligned) {
  1950. free(encoder->private_->windowed_signal_unaligned);
  1951. encoder->private_->windowed_signal_unaligned = 0;
  1952. }
  1953. #endif
  1954. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  1955. for(i = 0; i < 2; i++) {
  1956. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  1957. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  1958. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  1959. }
  1960. }
  1961. }
  1962. for(channel = 0; channel < 2; channel++) {
  1963. for(i = 0; i < 2; i++) {
  1964. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  1965. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  1966. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  1967. }
  1968. }
  1969. }
  1970. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  1971. free(encoder->private_->abs_residual_partition_sums_unaligned);
  1972. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  1973. }
  1974. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  1975. free(encoder->private_->raw_bits_per_partition_unaligned);
  1976. encoder->private_->raw_bits_per_partition_unaligned = 0;
  1977. }
  1978. if(encoder->protected_->verify) {
  1979. for(i = 0; i < encoder->protected_->channels; i++) {
  1980. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  1981. free(encoder->private_->verify.input_fifo.data[i]);
  1982. encoder->private_->verify.input_fifo.data[i] = 0;
  1983. }
  1984. }
  1985. }
  1986. FLAC__bitwriter_free(encoder->private_->frame);
  1987. }
  1988. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  1989. {
  1990. FLAC__bool ok;
  1991. unsigned i, channel;
  1992. FLAC__ASSERT(new_blocksize > 0);
  1993. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  1994. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  1995. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  1996. if(new_blocksize <= encoder->private_->input_capacity)
  1997. return true;
  1998. ok = true;
  1999. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  2000. * requires that the input arrays (in our case the integer signals)
  2001. * have a buffer of up to 3 zeroes in front (at negative indices) for
  2002. * alignment purposes; we use 4 in front to keep the data well-aligned.
  2003. */
  2004. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  2005. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  2006. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  2007. encoder->private_->integer_signal[i] += 4;
  2008. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  2009. #if 0 /* @@@ currently unused */
  2010. if(encoder->protected_->max_lpc_order > 0)
  2011. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  2012. #endif
  2013. #endif
  2014. }
  2015. for(i = 0; ok && i < 2; i++) {
  2016. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
  2017. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  2018. encoder->private_->integer_signal_mid_side[i] += 4;
  2019. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  2020. #if 0 /* @@@ currently unused */
  2021. if(encoder->protected_->max_lpc_order > 0)
  2022. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
  2023. #endif
  2024. #endif
  2025. }
  2026. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  2027. if(ok && encoder->protected_->max_lpc_order > 0) {
  2028. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  2029. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  2030. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  2031. }
  2032. #endif
  2033. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  2034. for(i = 0; ok && i < 2; i++) {
  2035. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  2036. }
  2037. }
  2038. for(channel = 0; ok && channel < 2; channel++) {
  2039. for(i = 0; ok && i < 2; i++) {
  2040. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
  2041. }
  2042. }
  2043. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  2044. /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
  2045. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  2046. if(encoder->protected_->do_escape_coding)
  2047. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  2048. /* now adjust the windows if the blocksize has changed */
  2049. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  2050. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  2051. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  2052. switch(encoder->protected_->apodizations[i].type) {
  2053. case FLAC__APODIZATION_BARTLETT:
  2054. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  2055. break;
  2056. case FLAC__APODIZATION_BARTLETT_HANN:
  2057. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  2058. break;
  2059. case FLAC__APODIZATION_BLACKMAN:
  2060. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  2061. break;
  2062. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  2063. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  2064. break;
  2065. case FLAC__APODIZATION_CONNES:
  2066. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  2067. break;
  2068. case FLAC__APODIZATION_FLATTOP:
  2069. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  2070. break;
  2071. case FLAC__APODIZATION_GAUSS:
  2072. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  2073. break;
  2074. case FLAC__APODIZATION_HAMMING:
  2075. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  2076. break;
  2077. case FLAC__APODIZATION_HANN:
  2078. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  2079. break;
  2080. case FLAC__APODIZATION_KAISER_BESSEL:
  2081. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  2082. break;
  2083. case FLAC__APODIZATION_NUTTALL:
  2084. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  2085. break;
  2086. case FLAC__APODIZATION_RECTANGLE:
  2087. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  2088. break;
  2089. case FLAC__APODIZATION_TRIANGLE:
  2090. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  2091. break;
  2092. case FLAC__APODIZATION_TUKEY:
  2093. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  2094. break;
  2095. case FLAC__APODIZATION_WELCH:
  2096. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  2097. break;
  2098. default:
  2099. FLAC__ASSERT(0);
  2100. /* double protection */
  2101. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  2102. break;
  2103. }
  2104. }
  2105. }
  2106. #endif
  2107. if(ok)
  2108. encoder->private_->input_capacity = new_blocksize;
  2109. else
  2110. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  2111. return ok;
  2112. }
  2113. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  2114. {
  2115. const FLAC__byte *buffer;
  2116. size_t bytes;
  2117. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  2118. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  2119. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  2120. return false;
  2121. }
  2122. if(encoder->protected_->verify) {
  2123. encoder->private_->verify.output.data = buffer;
  2124. encoder->private_->verify.output.bytes = bytes;
  2125. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  2126. encoder->private_->verify.needs_magic_hack = true;
  2127. }
  2128. else {
  2129. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  2130. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  2131. FLAC__bitwriter_clear(encoder->private_->frame);
  2132. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  2133. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  2134. return false;
  2135. }
  2136. }
  2137. }
  2138. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  2139. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  2140. FLAC__bitwriter_clear(encoder->private_->frame);
  2141. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2142. return false;
  2143. }
  2144. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  2145. FLAC__bitwriter_clear(encoder->private_->frame);
  2146. if(samples > 0) {
  2147. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  2148. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  2149. }
  2150. return true;
  2151. }
  2152. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  2153. {
  2154. (void) is_last_block;
  2155. FLAC__StreamEncoderWriteStatus status;
  2156. FLAC__uint64 output_position = 0;
  2157. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  2158. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  2159. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2160. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  2161. }
  2162. /*
  2163. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  2164. */
  2165. if(samples == 0) {
  2166. FLAC__MetadataType type = (buffer[0] & 0x7f);
  2167. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  2168. encoder->protected_->streaminfo_offset = output_position;
  2169. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  2170. encoder->protected_->seektable_offset = output_position;
  2171. }
  2172. /*
  2173. * Mark the current seek point if hit (if audio_offset == 0 that
  2174. * means we're still writing metadata and haven't hit the first
  2175. * frame yet)
  2176. */
  2177. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  2178. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  2179. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  2180. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  2181. FLAC__uint64 test_sample;
  2182. unsigned i;
  2183. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  2184. test_sample = encoder->private_->seek_table->points[i].sample_number;
  2185. if(test_sample > frame_last_sample) {
  2186. break;
  2187. }
  2188. else if(test_sample >= frame_first_sample) {
  2189. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  2190. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  2191. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  2192. encoder->private_->first_seekpoint_to_check++;
  2193. /* DO NOT: "break;" and here's why:
  2194. * The seektable template may contain more than one target
  2195. * sample for any given frame; we will keep looping, generating
  2196. * duplicate seekpoints for them, and we'll clean it up later,
  2197. * just before writing the seektable back to the metadata.
  2198. */
  2199. }
  2200. else {
  2201. encoder->private_->first_seekpoint_to_check++;
  2202. }
  2203. }
  2204. }
  2205. #if FLAC__HAS_OGG
  2206. if(encoder->private_->is_ogg) {
  2207. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  2208. &encoder->protected_->ogg_encoder_aspect,
  2209. buffer,
  2210. bytes,
  2211. samples,
  2212. encoder->private_->current_frame_number,
  2213. is_last_block,
  2214. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  2215. encoder,
  2216. encoder->private_->client_data
  2217. );
  2218. }
  2219. else
  2220. #endif
  2221. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  2222. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  2223. encoder->private_->bytes_written += bytes;
  2224. encoder->private_->samples_written += samples;
  2225. /* we keep a high watermark on the number of frames written because
  2226. * when the encoder goes back to write metadata, 'current_frame'
  2227. * will drop back to 0.
  2228. */
  2229. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  2230. }
  2231. else
  2232. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2233. return status;
  2234. }
  2235. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  2236. void update_metadata_(const FLAC__StreamEncoder *encoder)
  2237. {
  2238. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  2239. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  2240. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  2241. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  2242. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  2243. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  2244. FLAC__StreamEncoderSeekStatus seek_status;
  2245. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  2246. /* All this is based on intimate knowledge of the stream header
  2247. * layout, but a change to the header format that would break this
  2248. * would also break all streams encoded in the previous format.
  2249. */
  2250. /*
  2251. * Write MD5 signature
  2252. */
  2253. {
  2254. const unsigned md5_offset =
  2255. FLAC__STREAM_METADATA_HEADER_LENGTH +
  2256. (
  2257. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  2258. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  2259. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  2260. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  2261. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  2262. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  2263. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  2264. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  2265. ) / 8;
  2266. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  2267. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  2268. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2269. return;
  2270. }
  2271. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  2272. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2273. return;
  2274. }
  2275. }
  2276. /*
  2277. * Write total samples
  2278. */
  2279. {
  2280. const unsigned total_samples_byte_offset =
  2281. FLAC__STREAM_METADATA_HEADER_LENGTH +
  2282. (
  2283. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  2284. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  2285. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  2286. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  2287. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  2288. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  2289. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  2290. - 4
  2291. ) / 8;
  2292. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  2293. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  2294. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  2295. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  2296. b[4] = (FLAC__byte)(samples & 0xFF);
  2297. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + total_samples_byte_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  2298. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  2299. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2300. return;
  2301. }
  2302. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  2303. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2304. return;
  2305. }
  2306. }
  2307. /*
  2308. * Write min/max framesize
  2309. */
  2310. {
  2311. const unsigned min_framesize_offset =
  2312. FLAC__STREAM_METADATA_HEADER_LENGTH +
  2313. (
  2314. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  2315. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  2316. ) / 8;
  2317. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  2318. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  2319. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  2320. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  2321. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  2322. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  2323. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + min_framesize_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  2324. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  2325. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2326. return;
  2327. }
  2328. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  2329. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2330. return;
  2331. }
  2332. }
  2333. /*
  2334. * Write seektable
  2335. */
  2336. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  2337. unsigned i;
  2338. FLAC__format_seektable_sort(encoder->private_->seek_table);
  2339. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  2340. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->seektable_offset + FLAC__STREAM_METADATA_HEADER_LENGTH, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  2341. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  2342. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2343. return;
  2344. }
  2345. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  2346. FLAC__uint64 xx;
  2347. unsigned x;
  2348. xx = encoder->private_->seek_table->points[i].sample_number;
  2349. b[7] = (FLAC__byte)xx; xx >>= 8;
  2350. b[6] = (FLAC__byte)xx; xx >>= 8;
  2351. b[5] = (FLAC__byte)xx; xx >>= 8;
  2352. b[4] = (FLAC__byte)xx; xx >>= 8;
  2353. b[3] = (FLAC__byte)xx; xx >>= 8;
  2354. b[2] = (FLAC__byte)xx; xx >>= 8;
  2355. b[1] = (FLAC__byte)xx; xx >>= 8;
  2356. b[0] = (FLAC__byte)xx; xx >>= 8;
  2357. xx = encoder->private_->seek_table->points[i].stream_offset;
  2358. b[15] = (FLAC__byte)xx; xx >>= 8;
  2359. b[14] = (FLAC__byte)xx; xx >>= 8;
  2360. b[13] = (FLAC__byte)xx; xx >>= 8;
  2361. b[12] = (FLAC__byte)xx; xx >>= 8;
  2362. b[11] = (FLAC__byte)xx; xx >>= 8;
  2363. b[10] = (FLAC__byte)xx; xx >>= 8;
  2364. b[9] = (FLAC__byte)xx; xx >>= 8;
  2365. b[8] = (FLAC__byte)xx; xx >>= 8;
  2366. x = encoder->private_->seek_table->points[i].frame_samples;
  2367. b[17] = (FLAC__byte)x; x >>= 8;
  2368. b[16] = (FLAC__byte)x; x >>= 8;
  2369. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  2370. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  2371. return;
  2372. }
  2373. }
  2374. }
  2375. }
  2376. #if FLAC__HAS_OGG
  2377. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  2378. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  2379. {
  2380. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  2381. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  2382. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  2383. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  2384. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  2385. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  2386. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  2387. FLAC__STREAM_SYNC_LENGTH
  2388. ;
  2389. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  2390. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  2391. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  2392. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  2393. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  2394. ogg_page page;
  2395. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  2396. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  2397. /* Pre-check that client supports seeking, since we don't want the
  2398. * ogg_helper code to ever have to deal with this condition.
  2399. */
  2400. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  2401. return;
  2402. /* All this is based on intimate knowledge of the stream header
  2403. * layout, but a change to the header format that would break this
  2404. * would also break all streams encoded in the previous format.
  2405. */
  2406. /**
  2407. ** Write STREAMINFO stats
  2408. **/
  2409. simple_ogg_page__init(&page);
  2410. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  2411. simple_ogg_page__clear(&page);
  2412. return; /* state already set */
  2413. }
  2414. /*
  2415. * Write MD5 signature
  2416. */
  2417. {
  2418. const unsigned md5_offset =
  2419. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  2420. FLAC__STREAM_METADATA_HEADER_LENGTH +
  2421. (
  2422. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  2423. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  2424. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  2425. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  2426. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  2427. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  2428. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  2429. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  2430. ) / 8;
  2431. if(md5_offset + 16 > (unsigned)page.body_len) {
  2432. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  2433. simple_ogg_page__clear(&page);
  2434. return;
  2435. }
  2436. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  2437. }
  2438. /*
  2439. * Write total samples
  2440. */
  2441. {
  2442. const unsigned total_samples_byte_offset =
  2443. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  2444. FLAC__STREAM_METADATA_HEADER_LENGTH +
  2445. (
  2446. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  2447. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  2448. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  2449. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  2450. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  2451. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  2452. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  2453. - 4
  2454. ) / 8;
  2455. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  2456. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  2457. simple_ogg_page__clear(&page);
  2458. return;
  2459. }
  2460. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  2461. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  2462. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  2463. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  2464. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  2465. b[4] = (FLAC__byte)(samples & 0xFF);
  2466. memcpy(page.body + total_samples_byte_offset, b, 5);
  2467. }
  2468. /*
  2469. * Write min/max framesize
  2470. */
  2471. {
  2472. const unsigned min_framesize_offset =
  2473. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  2474. FLAC__STREAM_METADATA_HEADER_LENGTH +
  2475. (
  2476. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  2477. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  2478. ) / 8;
  2479. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  2480. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  2481. simple_ogg_page__clear(&page);
  2482. return;
  2483. }
  2484. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  2485. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  2486. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  2487. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  2488. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  2489. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  2490. memcpy(page.body + min_framesize_offset, b, 6);
  2491. }
  2492. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  2493. simple_ogg_page__clear(&page);
  2494. return; /* state already set */
  2495. }
  2496. simple_ogg_page__clear(&page);
  2497. /*
  2498. * Write seektable
  2499. */
  2500. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  2501. unsigned i;
  2502. FLAC__byte *p;
  2503. FLAC__format_seektable_sort(encoder->private_->seek_table);
  2504. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  2505. simple_ogg_page__init(&page);
  2506. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  2507. simple_ogg_page__clear(&page);
  2508. return; /* state already set */
  2509. }
  2510. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  2511. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  2512. simple_ogg_page__clear(&page);
  2513. return;
  2514. }
  2515. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  2516. FLAC__uint64 xx;
  2517. unsigned x;
  2518. xx = encoder->private_->seek_table->points[i].sample_number;
  2519. b[7] = (FLAC__byte)xx; xx >>= 8;
  2520. b[6] = (FLAC__byte)xx; xx >>= 8;
  2521. b[5] = (FLAC__byte)xx; xx >>= 8;
  2522. b[4] = (FLAC__byte)xx; xx >>= 8;
  2523. b[3] = (FLAC__byte)xx; xx >>= 8;
  2524. b[2] = (FLAC__byte)xx; xx >>= 8;
  2525. b[1] = (FLAC__byte)xx; xx >>= 8;
  2526. b[0] = (FLAC__byte)xx; xx >>= 8;
  2527. xx = encoder->private_->seek_table->points[i].stream_offset;
  2528. b[15] = (FLAC__byte)xx; xx >>= 8;
  2529. b[14] = (FLAC__byte)xx; xx >>= 8;
  2530. b[13] = (FLAC__byte)xx; xx >>= 8;
  2531. b[12] = (FLAC__byte)xx; xx >>= 8;
  2532. b[11] = (FLAC__byte)xx; xx >>= 8;
  2533. b[10] = (FLAC__byte)xx; xx >>= 8;
  2534. b[9] = (FLAC__byte)xx; xx >>= 8;
  2535. b[8] = (FLAC__byte)xx; xx >>= 8;
  2536. x = encoder->private_->seek_table->points[i].frame_samples;
  2537. b[17] = (FLAC__byte)x; x >>= 8;
  2538. b[16] = (FLAC__byte)x; x >>= 8;
  2539. memcpy(p, b, 18);
  2540. }
  2541. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  2542. simple_ogg_page__clear(&page);
  2543. return; /* state already set */
  2544. }
  2545. simple_ogg_page__clear(&page);
  2546. }
  2547. }
  2548. #endif
  2549. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  2550. {
  2551. FLAC__uint16 crc;
  2552. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  2553. /*
  2554. * Accumulate raw signal to the MD5 signature
  2555. */
  2556. if(encoder->protected_->do_md5 && !FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
  2557. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  2558. return false;
  2559. }
  2560. /*
  2561. * Process the frame header and subframes into the frame bitbuffer
  2562. */
  2563. if(!process_subframes_(encoder, is_fractional_block)) {
  2564. /* the above function sets the state for us in case of an error */
  2565. return false;
  2566. }
  2567. /*
  2568. * Zero-pad the frame to a byte_boundary
  2569. */
  2570. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  2571. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  2572. return false;
  2573. }
  2574. /*
  2575. * CRC-16 the whole thing
  2576. */
  2577. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  2578. if(
  2579. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  2580. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  2581. ) {
  2582. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  2583. return false;
  2584. }
  2585. /*
  2586. * Write it
  2587. */
  2588. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  2589. /* the above function sets the state for us in case of an error */
  2590. return false;
  2591. }
  2592. /*
  2593. * Get ready for the next frame
  2594. */
  2595. encoder->private_->current_sample_number = 0;
  2596. encoder->private_->current_frame_number++;
  2597. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  2598. return true;
  2599. }
  2600. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  2601. {
  2602. FLAC__FrameHeader frame_header;
  2603. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  2604. FLAC__bool do_independent, do_mid_side;
  2605. /*
  2606. * Calculate the min,max Rice partition orders
  2607. */
  2608. if(is_fractional_block) {
  2609. max_partition_order = 0;
  2610. }
  2611. else {
  2612. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  2613. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  2614. }
  2615. min_partition_order = min(min_partition_order, max_partition_order);
  2616. /*
  2617. * Setup the frame
  2618. */
  2619. frame_header.blocksize = encoder->protected_->blocksize;
  2620. frame_header.sample_rate = encoder->protected_->sample_rate;
  2621. frame_header.channels = encoder->protected_->channels;
  2622. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  2623. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  2624. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  2625. frame_header.number.frame_number = encoder->private_->current_frame_number;
  2626. /*
  2627. * Figure out what channel assignments to try
  2628. */
  2629. if(encoder->protected_->do_mid_side_stereo) {
  2630. if(encoder->protected_->loose_mid_side_stereo) {
  2631. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  2632. do_independent = true;
  2633. do_mid_side = true;
  2634. }
  2635. else {
  2636. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  2637. do_mid_side = !do_independent;
  2638. }
  2639. }
  2640. else {
  2641. do_independent = true;
  2642. do_mid_side = true;
  2643. }
  2644. }
  2645. else {
  2646. do_independent = true;
  2647. do_mid_side = false;
  2648. }
  2649. FLAC__ASSERT(do_independent || do_mid_side);
  2650. /*
  2651. * Check for wasted bits; set effective bps for each subframe
  2652. */
  2653. if(do_independent) {
  2654. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  2655. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  2656. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  2657. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  2658. }
  2659. }
  2660. if(do_mid_side) {
  2661. FLAC__ASSERT(encoder->protected_->channels == 2);
  2662. for(channel = 0; channel < 2; channel++) {
  2663. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  2664. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  2665. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  2666. }
  2667. }
  2668. /*
  2669. * First do a normal encoding pass of each independent channel
  2670. */
  2671. if(do_independent) {
  2672. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  2673. if(!
  2674. process_subframe_(
  2675. encoder,
  2676. min_partition_order,
  2677. max_partition_order,
  2678. &frame_header,
  2679. encoder->private_->subframe_bps[channel],
  2680. encoder->private_->integer_signal[channel],
  2681. encoder->private_->subframe_workspace_ptr[channel],
  2682. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  2683. encoder->private_->residual_workspace[channel],
  2684. encoder->private_->best_subframe+channel,
  2685. encoder->private_->best_subframe_bits+channel
  2686. )
  2687. )
  2688. return false;
  2689. }
  2690. }
  2691. /*
  2692. * Now do mid and side channels if requested
  2693. */
  2694. if(do_mid_side) {
  2695. FLAC__ASSERT(encoder->protected_->channels == 2);
  2696. for(channel = 0; channel < 2; channel++) {
  2697. if(!
  2698. process_subframe_(
  2699. encoder,
  2700. min_partition_order,
  2701. max_partition_order,
  2702. &frame_header,
  2703. encoder->private_->subframe_bps_mid_side[channel],
  2704. encoder->private_->integer_signal_mid_side[channel],
  2705. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  2706. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  2707. encoder->private_->residual_workspace_mid_side[channel],
  2708. encoder->private_->best_subframe_mid_side+channel,
  2709. encoder->private_->best_subframe_bits_mid_side+channel
  2710. )
  2711. )
  2712. return false;
  2713. }
  2714. }
  2715. /*
  2716. * Compose the frame bitbuffer
  2717. */
  2718. if(do_mid_side) {
  2719. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  2720. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  2721. FLAC__ChannelAssignment channel_assignment;
  2722. FLAC__ASSERT(encoder->protected_->channels == 2);
  2723. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  2724. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  2725. }
  2726. else {
  2727. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  2728. unsigned min_bits;
  2729. int ca;
  2730. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  2731. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  2732. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  2733. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  2734. FLAC__ASSERT(do_independent && do_mid_side);
  2735. /* We have to figure out which channel assignent results in the smallest frame */
  2736. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  2737. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  2738. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  2739. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  2740. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  2741. min_bits = bits[channel_assignment];
  2742. for(ca = 1; ca <= 3; ca++) {
  2743. if(bits[ca] < min_bits) {
  2744. min_bits = bits[ca];
  2745. channel_assignment = (FLAC__ChannelAssignment)ca;
  2746. }
  2747. }
  2748. }
  2749. frame_header.channel_assignment = channel_assignment;
  2750. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  2751. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  2752. return false;
  2753. }
  2754. switch(channel_assignment) {
  2755. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  2756. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  2757. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  2758. break;
  2759. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  2760. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  2761. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  2762. break;
  2763. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  2764. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  2765. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  2766. break;
  2767. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  2768. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  2769. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  2770. break;
  2771. default:
  2772. FLAC__ASSERT(0);
  2773. }
  2774. switch(channel_assignment) {
  2775. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  2776. left_bps = encoder->private_->subframe_bps [0];
  2777. right_bps = encoder->private_->subframe_bps [1];
  2778. break;
  2779. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  2780. left_bps = encoder->private_->subframe_bps [0];
  2781. right_bps = encoder->private_->subframe_bps_mid_side[1];
  2782. break;
  2783. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  2784. left_bps = encoder->private_->subframe_bps_mid_side[1];
  2785. right_bps = encoder->private_->subframe_bps [1];
  2786. break;
  2787. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  2788. left_bps = encoder->private_->subframe_bps_mid_side[0];
  2789. right_bps = encoder->private_->subframe_bps_mid_side[1];
  2790. break;
  2791. default:
  2792. FLAC__ASSERT(0);
  2793. }
  2794. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  2795. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  2796. return false;
  2797. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  2798. return false;
  2799. }
  2800. else {
  2801. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  2802. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  2803. return false;
  2804. }
  2805. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  2806. if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
  2807. /* the above function sets the state for us in case of an error */
  2808. return false;
  2809. }
  2810. }
  2811. }
  2812. if(encoder->protected_->loose_mid_side_stereo) {
  2813. encoder->private_->loose_mid_side_stereo_frame_count++;
  2814. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  2815. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  2816. }
  2817. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  2818. return true;
  2819. }
  2820. FLAC__bool process_subframe_(
  2821. FLAC__StreamEncoder *encoder,
  2822. unsigned min_partition_order,
  2823. unsigned max_partition_order,
  2824. const FLAC__FrameHeader *frame_header,
  2825. unsigned subframe_bps,
  2826. const FLAC__int32 integer_signal[],
  2827. FLAC__Subframe *subframe[2],
  2828. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  2829. FLAC__int32 *residual[2],
  2830. unsigned *best_subframe,
  2831. unsigned *best_bits
  2832. )
  2833. {
  2834. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  2835. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  2836. #else
  2837. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  2838. #endif
  2839. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  2840. FLAC__double lpc_residual_bits_per_sample;
  2841. FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm routines need all the space */
  2842. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  2843. unsigned min_lpc_order, max_lpc_order, lpc_order;
  2844. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  2845. #endif
  2846. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  2847. unsigned rice_parameter;
  2848. unsigned _candidate_bits, _best_bits;
  2849. unsigned _best_subframe;
  2850. /* only use RICE2 partitions if stream bps > 16 */
  2851. const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  2852. FLAC__ASSERT(frame_header->blocksize > 0);
  2853. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  2854. _best_subframe = 0;
  2855. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  2856. _best_bits = UINT_MAX;
  2857. else
  2858. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  2859. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  2860. unsigned signal_is_constant = false;
  2861. guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
  2862. /* check for constant subframe */
  2863. if(
  2864. !encoder->private_->disable_constant_subframes &&
  2865. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  2866. fixed_residual_bits_per_sample[1] == 0.0
  2867. #else
  2868. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  2869. #endif
  2870. ) {
  2871. /* the above means it's possible all samples are the same value; now double-check it: */
  2872. unsigned i;
  2873. signal_is_constant = true;
  2874. for(i = 1; i < frame_header->blocksize; i++) {
  2875. if(integer_signal[0] != integer_signal[i]) {
  2876. signal_is_constant = false;
  2877. break;
  2878. }
  2879. }
  2880. }
  2881. if(signal_is_constant) {
  2882. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  2883. if(_candidate_bits < _best_bits) {
  2884. _best_subframe = !_best_subframe;
  2885. _best_bits = _candidate_bits;
  2886. }
  2887. }
  2888. else {
  2889. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  2890. /* encode fixed */
  2891. if(encoder->protected_->do_exhaustive_model_search) {
  2892. min_fixed_order = 0;
  2893. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  2894. }
  2895. else {
  2896. min_fixed_order = max_fixed_order = guess_fixed_order;
  2897. }
  2898. if(max_fixed_order >= frame_header->blocksize)
  2899. max_fixed_order = frame_header->blocksize - 1;
  2900. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  2901. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  2902. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  2903. continue; /* don't even try */
  2904. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
  2905. #else
  2906. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  2907. continue; /* don't even try */
  2908. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
  2909. #endif
  2910. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  2911. if(rice_parameter >= rice_parameter_limit) {
  2912. #ifdef DEBUG_VERBOSE
  2913. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  2914. #endif
  2915. rice_parameter = rice_parameter_limit - 1;
  2916. }
  2917. _candidate_bits =
  2918. evaluate_fixed_subframe_(
  2919. encoder,
  2920. integer_signal,
  2921. residual[!_best_subframe],
  2922. encoder->private_->abs_residual_partition_sums,
  2923. encoder->private_->raw_bits_per_partition,
  2924. frame_header->blocksize,
  2925. subframe_bps,
  2926. fixed_order,
  2927. rice_parameter,
  2928. rice_parameter_limit,
  2929. min_partition_order,
  2930. max_partition_order,
  2931. encoder->protected_->do_escape_coding,
  2932. encoder->protected_->rice_parameter_search_dist,
  2933. subframe[!_best_subframe],
  2934. partitioned_rice_contents[!_best_subframe]
  2935. );
  2936. if(_candidate_bits < _best_bits) {
  2937. _best_subframe = !_best_subframe;
  2938. _best_bits = _candidate_bits;
  2939. }
  2940. }
  2941. }
  2942. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  2943. /* encode lpc */
  2944. if(encoder->protected_->max_lpc_order > 0) {
  2945. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  2946. max_lpc_order = frame_header->blocksize-1;
  2947. else
  2948. max_lpc_order = encoder->protected_->max_lpc_order;
  2949. if(max_lpc_order > 0) {
  2950. unsigned a;
  2951. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  2952. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  2953. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  2954. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  2955. if(autoc[0] != 0.0) {
  2956. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  2957. if(encoder->protected_->do_exhaustive_model_search) {
  2958. min_lpc_order = 1;
  2959. }
  2960. else {
  2961. const unsigned guess_lpc_order =
  2962. FLAC__lpc_compute_best_order(
  2963. lpc_error,
  2964. max_lpc_order,
  2965. frame_header->blocksize,
  2966. subframe_bps + (
  2967. encoder->protected_->do_qlp_coeff_prec_search?
  2968. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  2969. encoder->protected_->qlp_coeff_precision
  2970. )
  2971. );
  2972. min_lpc_order = max_lpc_order = guess_lpc_order;
  2973. }
  2974. if(max_lpc_order >= frame_header->blocksize)
  2975. max_lpc_order = frame_header->blocksize - 1;
  2976. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  2977. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  2978. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  2979. continue; /* don't even try */
  2980. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  2981. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  2982. if(rice_parameter >= rice_parameter_limit) {
  2983. #ifdef DEBUG_VERBOSE
  2984. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  2985. #endif
  2986. rice_parameter = rice_parameter_limit - 1;
  2987. }
  2988. if(encoder->protected_->do_qlp_coeff_prec_search) {
  2989. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  2990. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  2991. if(subframe_bps <= 17) {
  2992. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  2993. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  2994. }
  2995. else
  2996. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  2997. }
  2998. else {
  2999. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  3000. }
  3001. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  3002. _candidate_bits =
  3003. evaluate_lpc_subframe_(
  3004. encoder,
  3005. integer_signal,
  3006. residual[!_best_subframe],
  3007. encoder->private_->abs_residual_partition_sums,
  3008. encoder->private_->raw_bits_per_partition,
  3009. encoder->private_->lp_coeff[lpc_order-1],
  3010. frame_header->blocksize,
  3011. subframe_bps,
  3012. lpc_order,
  3013. qlp_coeff_precision,
  3014. rice_parameter,
  3015. rice_parameter_limit,
  3016. min_partition_order,
  3017. max_partition_order,
  3018. encoder->protected_->do_escape_coding,
  3019. encoder->protected_->rice_parameter_search_dist,
  3020. subframe[!_best_subframe],
  3021. partitioned_rice_contents[!_best_subframe]
  3022. );
  3023. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  3024. if(_candidate_bits < _best_bits) {
  3025. _best_subframe = !_best_subframe;
  3026. _best_bits = _candidate_bits;
  3027. }
  3028. }
  3029. }
  3030. }
  3031. }
  3032. }
  3033. }
  3034. }
  3035. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  3036. }
  3037. }
  3038. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  3039. if(_best_bits == UINT_MAX) {
  3040. FLAC__ASSERT(_best_subframe == 0);
  3041. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  3042. }
  3043. *best_subframe = _best_subframe;
  3044. *best_bits = _best_bits;
  3045. return true;
  3046. }
  3047. FLAC__bool add_subframe_(
  3048. FLAC__StreamEncoder *encoder,
  3049. unsigned blocksize,
  3050. unsigned subframe_bps,
  3051. const FLAC__Subframe *subframe,
  3052. FLAC__BitWriter *frame
  3053. )
  3054. {
  3055. switch(subframe->type) {
  3056. case FLAC__SUBFRAME_TYPE_CONSTANT:
  3057. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  3058. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  3059. return false;
  3060. }
  3061. break;
  3062. case FLAC__SUBFRAME_TYPE_FIXED:
  3063. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  3064. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  3065. return false;
  3066. }
  3067. break;
  3068. case FLAC__SUBFRAME_TYPE_LPC:
  3069. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  3070. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  3071. return false;
  3072. }
  3073. break;
  3074. case FLAC__SUBFRAME_TYPE_VERBATIM:
  3075. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  3076. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  3077. return false;
  3078. }
  3079. break;
  3080. default:
  3081. FLAC__ASSERT(0);
  3082. }
  3083. return true;
  3084. }
  3085. #define SPOTCHECK_ESTIMATE 0
  3086. #if SPOTCHECK_ESTIMATE
  3087. static void spotcheck_subframe_estimate_(
  3088. FLAC__StreamEncoder *encoder,
  3089. unsigned blocksize,
  3090. unsigned subframe_bps,
  3091. const FLAC__Subframe *subframe,
  3092. unsigned estimate
  3093. )
  3094. {
  3095. FLAC__bool ret;
  3096. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  3097. if(frame == 0) {
  3098. fprintf(stderr, "EST: can't allocate frame\n");
  3099. return;
  3100. }
  3101. if(!FLAC__bitwriter_init(frame)) {
  3102. fprintf(stderr, "EST: can't init frame\n");
  3103. return;
  3104. }
  3105. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  3106. FLAC__ASSERT(ret);
  3107. {
  3108. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  3109. if(estimate != actual)
  3110. fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
  3111. }
  3112. FLAC__bitwriter_delete(frame);
  3113. }
  3114. #endif
  3115. unsigned evaluate_constant_subframe_(
  3116. FLAC__StreamEncoder *encoder,
  3117. const FLAC__int32 signal,
  3118. unsigned blocksize,
  3119. unsigned subframe_bps,
  3120. FLAC__Subframe *subframe
  3121. )
  3122. {
  3123. unsigned estimate;
  3124. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  3125. subframe->data.constant.value = signal;
  3126. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  3127. #if SPOTCHECK_ESTIMATE
  3128. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  3129. #else
  3130. (void)encoder, (void)blocksize;
  3131. #endif
  3132. return estimate;
  3133. }
  3134. unsigned evaluate_fixed_subframe_(
  3135. FLAC__StreamEncoder *encoder,
  3136. const FLAC__int32 signal[],
  3137. FLAC__int32 residual[],
  3138. FLAC__uint64 abs_residual_partition_sums[],
  3139. unsigned raw_bits_per_partition[],
  3140. unsigned blocksize,
  3141. unsigned subframe_bps,
  3142. unsigned order,
  3143. unsigned rice_parameter,
  3144. unsigned rice_parameter_limit,
  3145. unsigned min_partition_order,
  3146. unsigned max_partition_order,
  3147. FLAC__bool do_escape_coding,
  3148. unsigned rice_parameter_search_dist,
  3149. FLAC__Subframe *subframe,
  3150. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  3151. )
  3152. {
  3153. unsigned i, residual_bits, estimate;
  3154. const unsigned residual_samples = blocksize - order;
  3155. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  3156. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  3157. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  3158. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  3159. subframe->data.fixed.residual = residual;
  3160. residual_bits =
  3161. find_best_partition_order_(
  3162. encoder->private_,
  3163. residual,
  3164. abs_residual_partition_sums,
  3165. raw_bits_per_partition,
  3166. residual_samples,
  3167. order,
  3168. rice_parameter,
  3169. rice_parameter_limit,
  3170. min_partition_order,
  3171. max_partition_order,
  3172. subframe_bps,
  3173. do_escape_coding,
  3174. rice_parameter_search_dist,
  3175. &subframe->data.fixed.entropy_coding_method
  3176. );
  3177. subframe->data.fixed.order = order;
  3178. for(i = 0; i < order; i++)
  3179. subframe->data.fixed.warmup[i] = signal[i];
  3180. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  3181. #if SPOTCHECK_ESTIMATE
  3182. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  3183. #endif
  3184. return estimate;
  3185. }
  3186. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  3187. unsigned evaluate_lpc_subframe_(
  3188. FLAC__StreamEncoder *encoder,
  3189. const FLAC__int32 signal[],
  3190. FLAC__int32 residual[],
  3191. FLAC__uint64 abs_residual_partition_sums[],
  3192. unsigned raw_bits_per_partition[],
  3193. const FLAC__real lp_coeff[],
  3194. unsigned blocksize,
  3195. unsigned subframe_bps,
  3196. unsigned order,
  3197. unsigned qlp_coeff_precision,
  3198. unsigned rice_parameter,
  3199. unsigned rice_parameter_limit,
  3200. unsigned min_partition_order,
  3201. unsigned max_partition_order,
  3202. FLAC__bool do_escape_coding,
  3203. unsigned rice_parameter_search_dist,
  3204. FLAC__Subframe *subframe,
  3205. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  3206. )
  3207. {
  3208. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  3209. unsigned i, residual_bits, estimate;
  3210. int quantization, ret;
  3211. const unsigned residual_samples = blocksize - order;
  3212. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  3213. if(subframe_bps <= 16) {
  3214. FLAC__ASSERT(order > 0);
  3215. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  3216. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  3217. }
  3218. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  3219. if(ret != 0)
  3220. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  3221. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  3222. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  3223. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  3224. else
  3225. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  3226. else
  3227. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  3228. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  3229. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  3230. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  3231. subframe->data.lpc.residual = residual;
  3232. residual_bits =
  3233. find_best_partition_order_(
  3234. encoder->private_,
  3235. residual,
  3236. abs_residual_partition_sums,
  3237. raw_bits_per_partition,
  3238. residual_samples,
  3239. order,
  3240. rice_parameter,
  3241. rice_parameter_limit,
  3242. min_partition_order,
  3243. max_partition_order,
  3244. subframe_bps,
  3245. do_escape_coding,
  3246. rice_parameter_search_dist,
  3247. &subframe->data.lpc.entropy_coding_method
  3248. );
  3249. subframe->data.lpc.order = order;
  3250. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  3251. subframe->data.lpc.quantization_level = quantization;
  3252. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  3253. for(i = 0; i < order; i++)
  3254. subframe->data.lpc.warmup[i] = signal[i];
  3255. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
  3256. #if SPOTCHECK_ESTIMATE
  3257. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  3258. #endif
  3259. return estimate;
  3260. }
  3261. #endif
  3262. unsigned evaluate_verbatim_subframe_(
  3263. FLAC__StreamEncoder *encoder,
  3264. const FLAC__int32 signal[],
  3265. unsigned blocksize,
  3266. unsigned subframe_bps,
  3267. FLAC__Subframe *subframe
  3268. )
  3269. {
  3270. unsigned estimate;
  3271. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  3272. subframe->data.verbatim.data = signal;
  3273. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  3274. #if SPOTCHECK_ESTIMATE
  3275. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  3276. #else
  3277. (void)encoder;
  3278. #endif
  3279. return estimate;
  3280. }
  3281. unsigned find_best_partition_order_(
  3282. FLAC__StreamEncoderPrivate *private_,
  3283. const FLAC__int32 residual[],
  3284. FLAC__uint64 abs_residual_partition_sums[],
  3285. unsigned raw_bits_per_partition[],
  3286. unsigned residual_samples,
  3287. unsigned predictor_order,
  3288. unsigned rice_parameter,
  3289. unsigned rice_parameter_limit,
  3290. unsigned min_partition_order,
  3291. unsigned max_partition_order,
  3292. unsigned bps,
  3293. FLAC__bool do_escape_coding,
  3294. unsigned rice_parameter_search_dist,
  3295. FLAC__EntropyCodingMethod *best_ecm
  3296. )
  3297. {
  3298. unsigned residual_bits, best_residual_bits = 0;
  3299. unsigned best_parameters_index = 0;
  3300. unsigned best_partition_order = 0;
  3301. const unsigned blocksize = residual_samples + predictor_order;
  3302. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  3303. min_partition_order = min(min_partition_order, max_partition_order);
  3304. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  3305. if(do_escape_coding)
  3306. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  3307. {
  3308. int partition_order;
  3309. unsigned sum;
  3310. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  3311. if(!
  3312. set_partitioned_rice_(
  3313. #ifdef EXACT_RICE_BITS_CALCULATION
  3314. residual,
  3315. #endif
  3316. abs_residual_partition_sums+sum,
  3317. raw_bits_per_partition+sum,
  3318. residual_samples,
  3319. predictor_order,
  3320. rice_parameter,
  3321. rice_parameter_limit,
  3322. rice_parameter_search_dist,
  3323. (unsigned)partition_order,
  3324. do_escape_coding,
  3325. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  3326. &residual_bits
  3327. )
  3328. )
  3329. {
  3330. FLAC__ASSERT(best_residual_bits != 0);
  3331. break;
  3332. }
  3333. sum += 1u << partition_order;
  3334. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  3335. best_residual_bits = residual_bits;
  3336. best_parameters_index = !best_parameters_index;
  3337. best_partition_order = partition_order;
  3338. }
  3339. }
  3340. }
  3341. best_ecm->data.partitioned_rice.order = best_partition_order;
  3342. {
  3343. /*
  3344. * We are allowed to de-const the pointer based on our special
  3345. * knowledge; it is const to the outside world.
  3346. */
  3347. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  3348. unsigned partition;
  3349. /* save best parameters and raw_bits */
  3350. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  3351. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  3352. if(do_escape_coding)
  3353. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  3354. /*
  3355. * Now need to check if the type should be changed to
  3356. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  3357. * size of the rice parameters.
  3358. */
  3359. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  3360. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  3361. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  3362. break;
  3363. }
  3364. }
  3365. }
  3366. return best_residual_bits;
  3367. }
  3368. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  3369. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  3370. const FLAC__int32 residual[],
  3371. FLAC__uint64 abs_residual_partition_sums[],
  3372. unsigned blocksize,
  3373. unsigned predictor_order,
  3374. unsigned min_partition_order,
  3375. unsigned max_partition_order
  3376. );
  3377. #endif
  3378. void precompute_partition_info_sums_(
  3379. const FLAC__int32 residual[],
  3380. FLAC__uint64 abs_residual_partition_sums[],
  3381. unsigned residual_samples,
  3382. unsigned predictor_order,
  3383. unsigned min_partition_order,
  3384. unsigned max_partition_order,
  3385. unsigned bps
  3386. )
  3387. {
  3388. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  3389. unsigned partitions = 1u << max_partition_order;
  3390. FLAC__ASSERT(default_partition_samples > predictor_order);
  3391. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  3392. /* slightly pessimistic but still catches all common cases */
  3393. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  3394. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  3395. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  3396. return;
  3397. }
  3398. #endif
  3399. /* first do max_partition_order */
  3400. {
  3401. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  3402. /* slightly pessimistic but still catches all common cases */
  3403. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  3404. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  3405. FLAC__uint32 abs_residual_partition_sum;
  3406. for(partition = residual_sample = 0; partition < partitions; partition++) {
  3407. end += default_partition_samples;
  3408. abs_residual_partition_sum = 0;
  3409. for( ; residual_sample < end; residual_sample++)
  3410. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  3411. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  3412. }
  3413. }
  3414. else { /* have to pessimistically use 64 bits for accumulator */
  3415. FLAC__uint64 abs_residual_partition_sum;
  3416. for(partition = residual_sample = 0; partition < partitions; partition++) {
  3417. end += default_partition_samples;
  3418. abs_residual_partition_sum = 0;
  3419. for( ; residual_sample < end; residual_sample++)
  3420. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  3421. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  3422. }
  3423. }
  3424. }
  3425. /* now merge partitions for lower orders */
  3426. {
  3427. unsigned from_partition = 0, to_partition = partitions;
  3428. int partition_order;
  3429. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  3430. unsigned i;
  3431. partitions >>= 1;
  3432. for(i = 0; i < partitions; i++) {
  3433. abs_residual_partition_sums[to_partition++] =
  3434. abs_residual_partition_sums[from_partition ] +
  3435. abs_residual_partition_sums[from_partition+1];
  3436. from_partition += 2;
  3437. }
  3438. }
  3439. }
  3440. }
  3441. void precompute_partition_info_escapes_(
  3442. const FLAC__int32 residual[],
  3443. unsigned raw_bits_per_partition[],
  3444. unsigned residual_samples,
  3445. unsigned predictor_order,
  3446. unsigned min_partition_order,
  3447. unsigned max_partition_order
  3448. )
  3449. {
  3450. int partition_order;
  3451. unsigned from_partition, to_partition = 0;
  3452. const unsigned blocksize = residual_samples + predictor_order;
  3453. /* first do max_partition_order */
  3454. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  3455. FLAC__int32 r;
  3456. FLAC__uint32 rmax;
  3457. unsigned partition, partition_sample, partition_samples, residual_sample;
  3458. const unsigned partitions = 1u << partition_order;
  3459. const unsigned default_partition_samples = blocksize >> partition_order;
  3460. FLAC__ASSERT(default_partition_samples > predictor_order);
  3461. for(partition = residual_sample = 0; partition < partitions; partition++) {
  3462. partition_samples = default_partition_samples;
  3463. if(partition == 0)
  3464. partition_samples -= predictor_order;
  3465. rmax = 0;
  3466. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  3467. r = residual[residual_sample++];
  3468. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  3469. if(r < 0)
  3470. rmax |= ~r;
  3471. else
  3472. rmax |= r;
  3473. }
  3474. /* now we know all residual values are in the range [-rmax-1,rmax] */
  3475. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  3476. }
  3477. to_partition = partitions;
  3478. break; /*@@@ yuck, should remove the 'for' loop instead */
  3479. }
  3480. /* now merge partitions for lower orders */
  3481. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  3482. unsigned m;
  3483. unsigned i;
  3484. const unsigned partitions = 1u << partition_order;
  3485. for(i = 0; i < partitions; i++) {
  3486. m = raw_bits_per_partition[from_partition];
  3487. from_partition++;
  3488. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  3489. from_partition++;
  3490. to_partition++;
  3491. }
  3492. }
  3493. }
  3494. #ifdef EXACT_RICE_BITS_CALCULATION
  3495. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  3496. const unsigned rice_parameter,
  3497. const unsigned partition_samples,
  3498. const FLAC__int32 *residual
  3499. )
  3500. {
  3501. unsigned i, partition_bits =
  3502. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  3503. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  3504. ;
  3505. for(i = 0; i < partition_samples; i++)
  3506. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  3507. return partition_bits;
  3508. }
  3509. #else
  3510. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  3511. const unsigned rice_parameter,
  3512. const unsigned partition_samples,
  3513. const FLAC__uint64 abs_residual_partition_sum
  3514. )
  3515. {
  3516. return
  3517. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  3518. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  3519. (
  3520. rice_parameter?
  3521. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  3522. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  3523. )
  3524. - (partition_samples >> 1)
  3525. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  3526. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  3527. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  3528. * So the subtraction term tries to guess how many extra bits were contributed.
  3529. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  3530. */
  3531. ;
  3532. }
  3533. #endif
  3534. FLAC__bool set_partitioned_rice_(
  3535. #ifdef EXACT_RICE_BITS_CALCULATION
  3536. const FLAC__int32 residual[],
  3537. #endif
  3538. const FLAC__uint64 abs_residual_partition_sums[],
  3539. const unsigned raw_bits_per_partition[],
  3540. const unsigned residual_samples,
  3541. const unsigned predictor_order,
  3542. const unsigned suggested_rice_parameter,
  3543. const unsigned rice_parameter_limit,
  3544. const unsigned rice_parameter_search_dist,
  3545. const unsigned partition_order,
  3546. const FLAC__bool search_for_escapes,
  3547. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  3548. unsigned *bits
  3549. )
  3550. {
  3551. unsigned rice_parameter, partition_bits;
  3552. unsigned best_partition_bits, best_rice_parameter = 0;
  3553. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  3554. unsigned *parameters, *raw_bits;
  3555. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  3556. unsigned min_rice_parameter, max_rice_parameter;
  3557. #else
  3558. (void)rice_parameter_search_dist;
  3559. #endif
  3560. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  3561. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  3562. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  3563. parameters = partitioned_rice_contents->parameters;
  3564. raw_bits = partitioned_rice_contents->raw_bits;
  3565. if(partition_order == 0) {
  3566. best_partition_bits = (unsigned)(-1);
  3567. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  3568. if(rice_parameter_search_dist) {
  3569. if(suggested_rice_parameter < rice_parameter_search_dist)
  3570. min_rice_parameter = 0;
  3571. else
  3572. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  3573. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  3574. if(max_rice_parameter >= rice_parameter_limit) {
  3575. #ifdef DEBUG_VERBOSE
  3576. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  3577. #endif
  3578. max_rice_parameter = rice_parameter_limit - 1;
  3579. }
  3580. }
  3581. else
  3582. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  3583. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  3584. #else
  3585. rice_parameter = suggested_rice_parameter;
  3586. #endif
  3587. #ifdef EXACT_RICE_BITS_CALCULATION
  3588. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  3589. #else
  3590. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  3591. #endif
  3592. if(partition_bits < best_partition_bits) {
  3593. best_rice_parameter = rice_parameter;
  3594. best_partition_bits = partition_bits;
  3595. }
  3596. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  3597. }
  3598. #endif
  3599. if(search_for_escapes) {
  3600. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
  3601. if(partition_bits <= best_partition_bits) {
  3602. raw_bits[0] = raw_bits_per_partition[0];
  3603. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  3604. best_partition_bits = partition_bits;
  3605. }
  3606. else
  3607. raw_bits[0] = 0;
  3608. }
  3609. parameters[0] = best_rice_parameter;
  3610. bits_ += best_partition_bits;
  3611. }
  3612. else {
  3613. unsigned partition, residual_sample;
  3614. unsigned partition_samples;
  3615. FLAC__uint64 mean, k;
  3616. const unsigned partitions = 1u << partition_order;
  3617. for(partition = residual_sample = 0; partition < partitions; partition++) {
  3618. partition_samples = (residual_samples+predictor_order) >> partition_order;
  3619. if(partition == 0) {
  3620. if(partition_samples <= predictor_order)
  3621. return false;
  3622. else
  3623. partition_samples -= predictor_order;
  3624. }
  3625. mean = abs_residual_partition_sums[partition];
  3626. /* we are basically calculating the size in bits of the
  3627. * average residual magnitude in the partition:
  3628. * rice_parameter = floor(log2(mean/partition_samples))
  3629. * 'mean' is not a good name for the variable, it is
  3630. * actually the sum of magnitudes of all residual values
  3631. * in the partition, so the actual mean is
  3632. * mean/partition_samples
  3633. */
  3634. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  3635. ;
  3636. if(rice_parameter >= rice_parameter_limit) {
  3637. #ifdef DEBUG_VERBOSE
  3638. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  3639. #endif
  3640. rice_parameter = rice_parameter_limit - 1;
  3641. }
  3642. best_partition_bits = (unsigned)(-1);
  3643. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  3644. if(rice_parameter_search_dist) {
  3645. if(rice_parameter < rice_parameter_search_dist)
  3646. min_rice_parameter = 0;
  3647. else
  3648. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  3649. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  3650. if(max_rice_parameter >= rice_parameter_limit) {
  3651. #ifdef DEBUG_VERBOSE
  3652. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  3653. #endif
  3654. max_rice_parameter = rice_parameter_limit - 1;
  3655. }
  3656. }
  3657. else
  3658. min_rice_parameter = max_rice_parameter = rice_parameter;
  3659. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  3660. #endif
  3661. #ifdef EXACT_RICE_BITS_CALCULATION
  3662. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  3663. #else
  3664. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  3665. #endif
  3666. if(partition_bits < best_partition_bits) {
  3667. best_rice_parameter = rice_parameter;
  3668. best_partition_bits = partition_bits;
  3669. }
  3670. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  3671. }
  3672. #endif
  3673. if(search_for_escapes) {
  3674. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
  3675. if(partition_bits <= best_partition_bits) {
  3676. raw_bits[partition] = raw_bits_per_partition[partition];
  3677. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  3678. best_partition_bits = partition_bits;
  3679. }
  3680. else
  3681. raw_bits[partition] = 0;
  3682. }
  3683. parameters[partition] = best_rice_parameter;
  3684. bits_ += best_partition_bits;
  3685. residual_sample += partition_samples;
  3686. }
  3687. }
  3688. *bits = bits_;
  3689. return true;
  3690. }
  3691. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  3692. {
  3693. unsigned i, shift;
  3694. FLAC__int32 x = 0;
  3695. for(i = 0; i < samples && !(x&1); i++)
  3696. x |= signal[i];
  3697. if(x == 0) {
  3698. shift = 0;
  3699. }
  3700. else {
  3701. for(shift = 0; !(x&1); shift++)
  3702. x >>= 1;
  3703. }
  3704. if(shift > 0) {
  3705. for(i = 0; i < samples; i++)
  3706. signal[i] >>= shift;
  3707. }
  3708. return shift;
  3709. }
  3710. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  3711. {
  3712. unsigned channel;
  3713. for(channel = 0; channel < channels; channel++)
  3714. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  3715. fifo->tail += wide_samples;
  3716. FLAC__ASSERT(fifo->tail <= fifo->size);
  3717. }
  3718. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  3719. {
  3720. unsigned channel;
  3721. unsigned sample, wide_sample;
  3722. unsigned tail = fifo->tail;
  3723. sample = input_offset * channels;
  3724. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  3725. for(channel = 0; channel < channels; channel++)
  3726. fifo->data[channel][tail] = input[sample++];
  3727. tail++;
  3728. }
  3729. fifo->tail = tail;
  3730. FLAC__ASSERT(fifo->tail <= fifo->size);
  3731. }
  3732. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  3733. {
  3734. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  3735. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  3736. (void)decoder;
  3737. if(encoder->private_->verify.needs_magic_hack) {
  3738. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  3739. *bytes = FLAC__STREAM_SYNC_LENGTH;
  3740. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  3741. encoder->private_->verify.needs_magic_hack = false;
  3742. }
  3743. else {
  3744. if(encoded_bytes == 0) {
  3745. /*
  3746. * If we get here, a FIFO underflow has occurred,
  3747. * which means there is a bug somewhere.
  3748. */
  3749. FLAC__ASSERT(0);
  3750. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  3751. }
  3752. else if(encoded_bytes < *bytes)
  3753. *bytes = encoded_bytes;
  3754. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  3755. encoder->private_->verify.output.data += *bytes;
  3756. encoder->private_->verify.output.bytes -= *bytes;
  3757. }
  3758. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  3759. }
  3760. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  3761. {
  3762. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  3763. unsigned channel;
  3764. const unsigned channels = frame->header.channels;
  3765. const unsigned blocksize = frame->header.blocksize;
  3766. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  3767. (void)decoder;
  3768. for(channel = 0; channel < channels; channel++) {
  3769. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  3770. unsigned i, sample = 0;
  3771. FLAC__int32 expect = 0, got = 0;
  3772. for(i = 0; i < blocksize; i++) {
  3773. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  3774. sample = i;
  3775. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  3776. got = (FLAC__int32)buffer[channel][i];
  3777. break;
  3778. }
  3779. }
  3780. FLAC__ASSERT(i < blocksize);
  3781. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  3782. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  3783. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  3784. encoder->private_->verify.error_stats.channel = channel;
  3785. encoder->private_->verify.error_stats.sample = sample;
  3786. encoder->private_->verify.error_stats.expected = expect;
  3787. encoder->private_->verify.error_stats.got = got;
  3788. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  3789. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  3790. }
  3791. }
  3792. /* dequeue the frame from the fifo */
  3793. encoder->private_->verify.input_fifo.tail -= blocksize;
  3794. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  3795. for(channel = 0; channel < channels; channel++)
  3796. memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
  3797. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  3798. }
  3799. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  3800. {
  3801. (void)decoder, (void)metadata, (void)client_data;
  3802. }
  3803. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  3804. {
  3805. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  3806. (void)decoder, (void)status;
  3807. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  3808. }
  3809. FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  3810. {
  3811. (void)client_data;
  3812. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  3813. if (*bytes == 0) {
  3814. if (feof(encoder->private_->file))
  3815. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  3816. else if (ferror(encoder->private_->file))
  3817. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  3818. }
  3819. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  3820. }
  3821. FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  3822. {
  3823. (void)client_data;
  3824. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  3825. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  3826. else
  3827. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  3828. }
  3829. FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  3830. {
  3831. off_t offset;
  3832. (void)client_data;
  3833. offset = ftello(encoder->private_->file);
  3834. if(offset < 0) {
  3835. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  3836. }
  3837. else {
  3838. *absolute_byte_offset = (FLAC__uint64)offset;
  3839. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  3840. }
  3841. }
  3842. #ifdef FLAC__VALGRIND_TESTING
  3843. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  3844. {
  3845. size_t ret = fwrite(ptr, size, nmemb, stream);
  3846. if(!ferror(stream))
  3847. fflush(stream);
  3848. return ret;
  3849. }
  3850. #else
  3851. #define local__fwrite fwrite
  3852. #endif
  3853. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  3854. {
  3855. (void)client_data, (void)current_frame;
  3856. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  3857. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  3858. #if FLAC__HAS_OGG
  3859. /* We would like to be able to use 'samples > 0' in the
  3860. * clause here but currently because of the nature of our
  3861. * Ogg writing implementation, 'samples' is always 0 (see
  3862. * ogg_encoder_aspect.c). The downside is extra progress
  3863. * callbacks.
  3864. */
  3865. encoder->private_->is_ogg? true :
  3866. #endif
  3867. samples > 0
  3868. );
  3869. if(call_it) {
  3870. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  3871. * because at this point in the callback chain, the stats
  3872. * have not been updated. Only after we return and control
  3873. * gets back to write_frame_() are the stats updated
  3874. */
  3875. encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
  3876. }
  3877. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  3878. }
  3879. else
  3880. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  3881. }
  3882. /*
  3883. * This will forcibly set stdout to binary mode (for OSes that require it)
  3884. */
  3885. FILE *get_binary_stdout_(void)
  3886. {
  3887. /* if something breaks here it is probably due to the presence or
  3888. * absence of an underscore before the identifiers 'setmode',
  3889. * 'fileno', and/or 'O_BINARY'; check your system header files.
  3890. */
  3891. #if defined _MSC_VER || defined __MINGW32__
  3892. _setmode(_fileno(stdout), _O_BINARY);
  3893. #elif defined __CYGWIN__
  3894. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  3895. setmode(fileno(stdout), O_BINARY);
  3896. #elif defined __EMX__
  3897. setmode(fileno(stdout), O_BINARY);
  3898. #endif
  3899. return stdout;
  3900. }