Ctrl_smp.cpp 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792
  1. /*
  2. * Ctrl_smp.cpp
  3. * ------------
  4. * Purpose: Sample tab, upper panel.
  5. * Notes : (currently none)
  6. * Authors: Olivier Lapicque
  7. * OpenMPT Devs
  8. * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
  9. */
  10. #include "stdafx.h"
  11. #include "Mptrack.h"
  12. #include "Mainfrm.h"
  13. #include "InputHandler.h"
  14. #include "Childfrm.h"
  15. #include "ImageLists.h"
  16. #include "Moddoc.h"
  17. #include "../soundlib/mod_specifications.h"
  18. #include "Globals.h"
  19. #include "Ctrl_smp.h"
  20. #include "View_smp.h"
  21. #include "SampleEditorDialogs.h"
  22. #include "dlg_misc.h"
  23. #include "PSRatioCalc.h"
  24. #include <soundtouch/include/SoundTouch.h>
  25. #include <soundtouch/source/SoundTouchDLL/SoundTouchDLL.h>
  26. #include <smbPitchShift/smbPitchShift.h>
  27. #include "../tracklib/SampleEdit.h"
  28. #include "Autotune.h"
  29. #include "../common/mptStringBuffer.h"
  30. #include "../common/mptFileIO.h"
  31. #include "../common/FileReader.h"
  32. #include "openmpt/soundbase/Copy.hpp"
  33. #include "openmpt/soundbase/SampleConvert.hpp"
  34. #include "openmpt/soundbase/SampleDecode.hpp"
  35. #include "../soundlib/SampleCopy.h"
  36. #include "FileDialog.h"
  37. #include "ProgressDialog.h"
  38. #include "../include/r8brain/CDSPResampler.h"
  39. #include "../soundlib/MixFuncTable.h"
  40. #include "mpt/audio/span.hpp"
  41. OPENMPT_NAMESPACE_BEGIN
  42. #define BASENOTE_MIN (1*12) // C-1
  43. #define BASENOTE_MAX (10*12+11) // B-10
  44. BEGIN_MESSAGE_MAP(CCtrlSamples, CModControlDlg)
  45. //{{AFX_MSG_MAP(CCtrlSamples)
  46. ON_WM_VSCROLL()
  47. ON_WM_XBUTTONUP()
  48. ON_NOTIFY(TBN_DROPDOWN, IDC_TOOLBAR1, &CCtrlSamples::OnTbnDropDownToolBar)
  49. ON_COMMAND(IDC_SAMPLE_NEW, &CCtrlSamples::OnSampleNew)
  50. ON_COMMAND(IDC_SAMPLE_DUPLICATE, &CCtrlSamples::OnSampleDuplicate)
  51. ON_COMMAND(IDC_SAMPLE_OPEN, &CCtrlSamples::OnSampleOpen)
  52. ON_COMMAND(IDC_SAMPLE_OPENKNOWN, &CCtrlSamples::OnSampleOpenKnown)
  53. ON_COMMAND(IDC_SAMPLE_OPENRAW, &CCtrlSamples::OnSampleOpenRaw)
  54. ON_COMMAND(IDC_SAMPLE_SAVEAS, &CCtrlSamples::OnSampleSave)
  55. ON_COMMAND(IDC_SAVE_ONE, &CCtrlSamples::OnSampleSaveOne)
  56. ON_COMMAND(IDC_SAVE_ALL, &CCtrlSamples::OnSampleSaveAll)
  57. ON_COMMAND(IDC_SAMPLE_PLAY, &CCtrlSamples::OnSamplePlay)
  58. ON_COMMAND(IDC_SAMPLE_NORMALIZE, &CCtrlSamples::OnNormalize)
  59. ON_COMMAND(IDC_SAMPLE_AMPLIFY, &CCtrlSamples::OnAmplify)
  60. ON_COMMAND(IDC_SAMPLE_RESAMPLE, &CCtrlSamples::OnResample)
  61. ON_COMMAND(IDC_SAMPLE_REVERSE, &CCtrlSamples::OnReverse)
  62. ON_COMMAND(IDC_SAMPLE_SILENCE, &CCtrlSamples::OnSilence)
  63. ON_COMMAND(IDC_SAMPLE_INVERT, &CCtrlSamples::OnInvert)
  64. ON_COMMAND(IDC_SAMPLE_SIGN_UNSIGN, &CCtrlSamples::OnSignUnSign)
  65. ON_COMMAND(IDC_SAMPLE_DCOFFSET, &CCtrlSamples::OnRemoveDCOffset)
  66. ON_COMMAND(IDC_SAMPLE_XFADE, &CCtrlSamples::OnXFade)
  67. ON_COMMAND(IDC_SAMPLE_STEREOSEPARATION, &CCtrlSamples::OnStereoSeparation)
  68. ON_COMMAND(IDC_SAMPLE_AUTOTUNE, &CCtrlSamples::OnAutotune)
  69. ON_COMMAND(IDC_CHECK1, &CCtrlSamples::OnSetPanningChanged)
  70. ON_COMMAND(IDC_CHECK2, &CCtrlSamples::OnKeepSampleOnDisk)
  71. ON_COMMAND(ID_PREVINSTRUMENT, &CCtrlSamples::OnPrevInstrument)
  72. ON_COMMAND(ID_NEXTINSTRUMENT, &CCtrlSamples::OnNextInstrument)
  73. ON_COMMAND(IDC_BUTTON1, &CCtrlSamples::OnPitchShiftTimeStretch)
  74. ON_COMMAND(IDC_BUTTON2, &CCtrlSamples::OnEstimateSampleSize)
  75. ON_COMMAND(IDC_CHECK3, &CCtrlSamples::OnEnableStretchToSize)
  76. ON_COMMAND(IDC_SAMPLE_INITOPL, &CCtrlSamples::OnInitOPLInstrument)
  77. ON_EN_CHANGE(IDC_SAMPLE_NAME, &CCtrlSamples::OnNameChanged)
  78. ON_EN_CHANGE(IDC_SAMPLE_FILENAME, &CCtrlSamples::OnFileNameChanged)
  79. ON_EN_CHANGE(IDC_EDIT_SAMPLE, &CCtrlSamples::OnSampleChanged)
  80. ON_EN_CHANGE(IDC_EDIT1, &CCtrlSamples::OnLoopPointsChanged)
  81. ON_EN_CHANGE(IDC_EDIT2, &CCtrlSamples::OnLoopPointsChanged)
  82. ON_EN_CHANGE(IDC_EDIT3, &CCtrlSamples::OnSustainPointsChanged)
  83. ON_EN_CHANGE(IDC_EDIT4, &CCtrlSamples::OnSustainPointsChanged)
  84. ON_EN_CHANGE(IDC_EDIT5, &CCtrlSamples::OnFineTuneChanged)
  85. ON_EN_CHANGE(IDC_EDIT7, &CCtrlSamples::OnVolumeChanged)
  86. ON_EN_CHANGE(IDC_EDIT8, &CCtrlSamples::OnGlobalVolChanged)
  87. ON_EN_CHANGE(IDC_EDIT9, &CCtrlSamples::OnPanningChanged)
  88. ON_EN_CHANGE(IDC_EDIT14, &CCtrlSamples::OnVibSweepChanged)
  89. ON_EN_CHANGE(IDC_EDIT15, &CCtrlSamples::OnVibDepthChanged)
  90. ON_EN_CHANGE(IDC_EDIT16, &CCtrlSamples::OnVibRateChanged)
  91. ON_EN_SETFOCUS(IDC_SAMPLE_NAME, &CCtrlSamples::OnEditFocus)
  92. ON_EN_SETFOCUS(IDC_SAMPLE_FILENAME, &CCtrlSamples::OnEditFocus)
  93. ON_EN_SETFOCUS(IDC_EDIT1, &CCtrlSamples::OnEditFocus)
  94. ON_EN_SETFOCUS(IDC_EDIT2, &CCtrlSamples::OnEditFocus)
  95. ON_EN_SETFOCUS(IDC_EDIT3, &CCtrlSamples::OnEditFocus)
  96. ON_EN_SETFOCUS(IDC_EDIT4, &CCtrlSamples::OnEditFocus)
  97. ON_EN_SETFOCUS(IDC_EDIT5, &CCtrlSamples::OnEditFocus)
  98. ON_EN_SETFOCUS(IDC_EDIT7, &CCtrlSamples::OnEditFocus)
  99. ON_EN_SETFOCUS(IDC_EDIT8, &CCtrlSamples::OnEditFocus)
  100. ON_EN_SETFOCUS(IDC_EDIT9, &CCtrlSamples::OnEditFocus)
  101. ON_EN_SETFOCUS(IDC_EDIT14, &CCtrlSamples::OnEditFocus)
  102. ON_EN_SETFOCUS(IDC_EDIT15, &CCtrlSamples::OnEditFocus)
  103. ON_EN_SETFOCUS(IDC_EDIT16, &CCtrlSamples::OnEditFocus)
  104. ON_EN_KILLFOCUS(IDC_EDIT5, &CCtrlSamples::OnFineTuneChangedDone)
  105. ON_CBN_SELCHANGE(IDC_COMBO_BASENOTE,&CCtrlSamples::OnBaseNoteChanged)
  106. ON_CBN_SELCHANGE(IDC_COMBO_ZOOM, &CCtrlSamples::OnZoomChanged)
  107. ON_CBN_SELCHANGE(IDC_COMBO1, &CCtrlSamples::OnLoopTypeChanged)
  108. ON_CBN_SELCHANGE(IDC_COMBO2, &CCtrlSamples::OnSustainTypeChanged)
  109. ON_CBN_SELCHANGE(IDC_COMBO3, &CCtrlSamples::OnVibTypeChanged)
  110. ON_MESSAGE(WM_MOD_KEYCOMMAND, &CCtrlSamples::OnCustomKeyMsg)
  111. //}}AFX_MSG_MAP
  112. END_MESSAGE_MAP()
  113. void CCtrlSamples::DoDataExchange(CDataExchange* pDX)
  114. {
  115. CModControlDlg::DoDataExchange(pDX);
  116. //{{AFX_DATA_MAP(CCtrlSamples)
  117. DDX_Control(pDX, IDC_TOOLBAR1, m_ToolBar1);
  118. DDX_Control(pDX, IDC_TOOLBAR2, m_ToolBar2);
  119. DDX_Control(pDX, IDC_SAMPLE_NAME, m_EditName);
  120. DDX_Control(pDX, IDC_SAMPLE_FILENAME, m_EditFileName);
  121. DDX_Control(pDX, IDC_SAMPLE_NAME, m_EditName);
  122. DDX_Control(pDX, IDC_SAMPLE_FILENAME, m_EditFileName);
  123. DDX_Control(pDX, IDC_COMBO_ZOOM, m_ComboZoom);
  124. DDX_Control(pDX, IDC_COMBO_BASENOTE, m_CbnBaseNote);
  125. DDX_Control(pDX, IDC_SPIN_SAMPLE, m_SpinSample);
  126. DDX_Control(pDX, IDC_EDIT_SAMPLE, m_EditSample);
  127. DDX_Control(pDX, IDC_CHECK1, m_CheckPanning);
  128. DDX_Control(pDX, IDC_SPIN1, m_SpinLoopStart);
  129. DDX_Control(pDX, IDC_SPIN2, m_SpinLoopEnd);
  130. DDX_Control(pDX, IDC_SPIN3, m_SpinSustainStart);
  131. DDX_Control(pDX, IDC_SPIN4, m_SpinSustainEnd);
  132. DDX_Control(pDX, IDC_SPIN5, m_SpinFineTune);
  133. DDX_Control(pDX, IDC_SPIN7, m_SpinVolume);
  134. DDX_Control(pDX, IDC_SPIN8, m_SpinGlobalVol);
  135. DDX_Control(pDX, IDC_SPIN9, m_SpinPanning);
  136. DDX_Control(pDX, IDC_SPIN11, m_SpinVibSweep);
  137. DDX_Control(pDX, IDC_SPIN12, m_SpinVibDepth);
  138. DDX_Control(pDX, IDC_SPIN13, m_SpinVibRate);
  139. DDX_Control(pDX, IDC_COMBO1, m_ComboLoopType);
  140. DDX_Control(pDX, IDC_COMBO2, m_ComboSustainType);
  141. DDX_Control(pDX, IDC_COMBO3, m_ComboAutoVib);
  142. DDX_Control(pDX, IDC_EDIT1, m_EditLoopStart);
  143. DDX_Control(pDX, IDC_EDIT2, m_EditLoopEnd);
  144. DDX_Control(pDX, IDC_EDIT3, m_EditSustainStart);
  145. DDX_Control(pDX, IDC_EDIT4, m_EditSustainEnd);
  146. DDX_Control(pDX, IDC_EDIT5, m_EditFineTune);
  147. DDX_Control(pDX, IDC_EDIT7, m_EditVolume);
  148. DDX_Control(pDX, IDC_EDIT8, m_EditGlobalVol);
  149. DDX_Control(pDX, IDC_EDIT9, m_EditPanning);
  150. DDX_Control(pDX, IDC_EDIT14, m_EditVibSweep);
  151. DDX_Control(pDX, IDC_EDIT15, m_EditVibDepth);
  152. DDX_Control(pDX, IDC_EDIT16, m_EditVibRate);
  153. DDX_Control(pDX, IDC_COMBO4, m_ComboPitch);
  154. DDX_Control(pDX, IDC_COMBO5, m_ComboQuality);
  155. DDX_Control(pDX, IDC_COMBO6, m_ComboFFT);
  156. DDX_Control(pDX, IDC_SPIN10, m_SpinSequenceMs);
  157. DDX_Control(pDX, IDC_SPIN14, m_SpinSeekWindowMs);
  158. DDX_Control(pDX, IDC_SPIN15, m_SpinOverlap);
  159. DDX_Control(pDX, IDC_SPIN16, m_SpinStretchAmount);
  160. DDX_Text(pDX, IDC_EDIT6, m_dTimeStretchRatio);
  161. //}}AFX_DATA_MAP
  162. }
  163. CCtrlSamples::CCtrlSamples(CModControlView &parent, CModDoc &document)
  164. : CModControlDlg(parent, document)
  165. {
  166. m_nLockCount = 1;
  167. }
  168. CCtrlSamples::~CCtrlSamples()
  169. {
  170. }
  171. CRuntimeClass *CCtrlSamples::GetAssociatedViewClass()
  172. {
  173. return RUNTIME_CLASS(CViewSample);
  174. }
  175. void CCtrlSamples::OnEditFocus()
  176. {
  177. m_startedEdit = false;
  178. }
  179. BOOL CCtrlSamples::OnInitDialog()
  180. {
  181. CModControlDlg::OnInitDialog();
  182. m_bInitialized = FALSE;
  183. SetRedraw(FALSE);
  184. // Zoom Selection
  185. static constexpr std::pair<const TCHAR *, int> ZoomLevels[] =
  186. {
  187. {_T("Auto"), 0},
  188. {_T("1:1"), 1},
  189. {_T("2:1"), -2},
  190. {_T("4:1"), -3},
  191. {_T("8:1"), -4},
  192. {_T("16:1"), -5},
  193. {_T("32:1"), -6},
  194. {_T("1:2"), 2},
  195. {_T("1:4"), 3},
  196. {_T("1:8"), 4},
  197. {_T("1:16"), 5},
  198. {_T("1:32"), 6},
  199. {_T("1:64"), 7},
  200. {_T("1:128"), 8},
  201. {_T("1:256"), 9},
  202. {_T("1:512"), 10},
  203. };
  204. m_ComboZoom.SetRedraw(FALSE);
  205. m_ComboZoom.InitStorage(static_cast<int>(std::size(ZoomLevels)), 4);
  206. for(const auto &[str, data] : ZoomLevels)
  207. {
  208. m_ComboZoom.SetItemData(m_ComboZoom.AddString(str), static_cast<DWORD_PTR>(data));
  209. }
  210. m_ComboZoom.SetRedraw(TRUE);
  211. m_ComboZoom.SetCurSel(0);
  212. // File ToolBar
  213. m_ToolBar1.SetExtendedStyle(m_ToolBar1.GetExtendedStyle() | TBSTYLE_EX_DRAWDDARROWS);
  214. m_ToolBar1.Init(CMainFrame::GetMainFrame()->m_PatternIcons,CMainFrame::GetMainFrame()->m_PatternIconsDisabled);
  215. m_ToolBar1.AddButton(IDC_SAMPLE_NEW, TIMAGE_SAMPLE_NEW, TBSTYLE_BUTTON | TBSTYLE_DROPDOWN);
  216. m_ToolBar1.AddButton(IDC_SAMPLE_OPEN, TIMAGE_OPEN, TBSTYLE_BUTTON | TBSTYLE_DROPDOWN);
  217. m_ToolBar1.AddButton(IDC_SAMPLE_SAVEAS, TIMAGE_SAVE, TBSTYLE_BUTTON | TBSTYLE_DROPDOWN);
  218. // Edit ToolBar
  219. m_ToolBar2.Init(CMainFrame::GetMainFrame()->m_PatternIcons,CMainFrame::GetMainFrame()->m_PatternIconsDisabled);
  220. m_ToolBar2.AddButton(IDC_SAMPLE_PLAY, TIMAGE_PREVIEW);
  221. m_ToolBar2.AddButton(IDC_SAMPLE_NORMALIZE, TIMAGE_SAMPLE_NORMALIZE);
  222. m_ToolBar2.AddButton(IDC_SAMPLE_AMPLIFY, TIMAGE_SAMPLE_AMPLIFY);
  223. m_ToolBar2.AddButton(IDC_SAMPLE_DCOFFSET, TIMAGE_SAMPLE_DCOFFSET);
  224. m_ToolBar2.AddButton(IDC_SAMPLE_STEREOSEPARATION, TIMAGE_SAMPLE_STEREOSEP);
  225. m_ToolBar2.AddButton(IDC_SAMPLE_RESAMPLE, TIMAGE_SAMPLE_RESAMPLE);
  226. m_ToolBar2.AddButton(IDC_SAMPLE_REVERSE, TIMAGE_SAMPLE_REVERSE);
  227. m_ToolBar2.AddButton(IDC_SAMPLE_SILENCE, TIMAGE_SAMPLE_SILENCE);
  228. m_ToolBar2.AddButton(IDC_SAMPLE_INVERT, TIMAGE_SAMPLE_INVERT);
  229. m_ToolBar2.AddButton(IDC_SAMPLE_SIGN_UNSIGN, TIMAGE_SAMPLE_UNSIGN);
  230. m_ToolBar2.AddButton(IDC_SAMPLE_XFADE, TIMAGE_SAMPLE_FIXLOOP);
  231. m_ToolBar2.AddButton(IDC_SAMPLE_AUTOTUNE, TIMAGE_SAMPLE_AUTOTUNE);
  232. // Setup Controls
  233. m_SpinVolume.SetRange(0, 64);
  234. m_SpinGlobalVol.SetRange(0, 64);
  235. m_CbnBaseNote.InitStorage(BASENOTE_MAX - BASENOTE_MIN, 4);
  236. m_CbnBaseNote.SetRedraw(FALSE);
  237. for(ModCommand::NOTE i = BASENOTE_MIN; i <= BASENOTE_MAX; i++)
  238. {
  239. CString noteName = mpt::ToCString(CSoundFile::GetDefaultNoteName(i % 12)) + mpt::cfmt::val(i / 12);
  240. m_CbnBaseNote.SetItemData(m_CbnBaseNote.AddString(noteName), i - (NOTE_MIDDLEC - NOTE_MIN));
  241. }
  242. m_CbnBaseNote.SetRedraw(TRUE);
  243. m_ComboFFT.ShowWindow(SW_SHOW);
  244. m_ComboPitch.ShowWindow(SW_SHOW);
  245. m_ComboQuality.ShowWindow(SW_SHOW);
  246. m_ComboFFT.ShowWindow(SW_SHOW);
  247. // Pitch selection
  248. // Allow pitch from -12 (1 octave down) to +12 (1 octave up)
  249. m_ComboPitch.InitStorage(25, 4);
  250. m_ComboPitch.SetRedraw(FALSE);
  251. for(int i = -12 ; i <= 12 ; i++)
  252. {
  253. mpt::tstring str;
  254. if(i == 0)
  255. str = _T("none");
  256. else if(i < 0)
  257. str = mpt::tfmt::dec(i);
  258. else
  259. str = _T("+") + mpt::tfmt::dec(i);
  260. m_ComboPitch.SetItemData(m_ComboPitch.AddString(str.c_str()), i + 12);
  261. }
  262. m_ComboPitch.SetRedraw(TRUE);
  263. // Set "none" as default pitch
  264. m_ComboPitch.SetCurSel(12);
  265. // Quality selection
  266. // Allow quality from 4 to 128
  267. m_ComboQuality.InitStorage(128 - 4, 4);
  268. m_ComboQuality.SetRedraw(FALSE);
  269. for(int i = 4; i <= 128; i++)
  270. {
  271. m_ComboQuality.SetItemData(m_ComboQuality.AddString(mpt::tfmt::dec(i).c_str()), i - 4);
  272. }
  273. m_ComboQuality.SetRedraw(TRUE);
  274. // Set 32 as default quality
  275. m_ComboQuality.SetCurSel(32 - 4);
  276. // FFT size selection
  277. // Deduce exponent from equation : MAX_FRAME_LENGTH = 2^exponent
  278. constexpr int exponent = mpt::bit_width(uint32(MAX_FRAME_LENGTH)) - 1;
  279. // Allow FFT size from 2^8 (256) to 2^exponent (MAX_FRAME_LENGTH)
  280. m_ComboFFT.InitStorage(exponent - 8, 4);
  281. m_ComboFFT.SetRedraw(FALSE);
  282. for(int i = 8 ; i <= exponent ; i++)
  283. {
  284. m_ComboFFT.SetItemData(m_ComboFFT.AddString(mpt::tfmt::dec(1 << i).c_str()), i - 8);
  285. }
  286. m_ComboFFT.SetRedraw(TRUE);
  287. // Set 4096 as default FFT size
  288. m_ComboFFT.SetCurSel(4);
  289. // Stretch to size check box
  290. OnEnableStretchToSize();
  291. m_SpinSequenceMs.SetRange32(0, 9999);
  292. m_SpinSeekWindowMs.SetRange32(0, 9999);
  293. m_SpinOverlap.SetRange32(0, 9999);
  294. m_SpinStretchAmount.SetRange32(50, 200);
  295. SetRedraw(TRUE);
  296. return TRUE;
  297. }
  298. void CCtrlSamples::RecalcLayout()
  299. {
  300. }
  301. bool CCtrlSamples::SetCurrentSample(SAMPLEINDEX nSmp, LONG lZoom, bool bUpdNum)
  302. {
  303. if(m_sndFile.GetNumSamples() < 1)
  304. m_sndFile.m_nSamples = 1;
  305. if((nSmp < 1) || (nSmp > m_sndFile.GetNumSamples()))
  306. return FALSE;
  307. LockControls();
  308. if(m_nSample != nSmp)
  309. {
  310. m_nSample = nSmp;
  311. UpdateView(SampleHint(m_nSample).Info());
  312. m_parent.SampleChanged(m_nSample);
  313. }
  314. if(bUpdNum)
  315. {
  316. SetDlgItemInt(IDC_EDIT_SAMPLE, m_nSample);
  317. m_SpinSample.SetRange(1, m_sndFile.GetNumSamples());
  318. }
  319. if(lZoom == -1)
  320. {
  321. lZoom = static_cast<int>(m_ComboZoom.GetItemData(m_ComboZoom.GetCurSel()));
  322. } else
  323. {
  324. for(int i = 0; i< m_ComboZoom.GetCount(); i++)
  325. {
  326. if(static_cast<int>(m_ComboZoom.GetItemData(i)) == lZoom)
  327. {
  328. m_ComboZoom.SetCurSel(i);
  329. break;
  330. }
  331. }
  332. }
  333. static_assert(MAX_SAMPLES < uint16_max);
  334. SendViewMessage(VIEWMSG_SETCURRENTSAMPLE, (lZoom << 16) | m_nSample);
  335. UnlockControls();
  336. return true;
  337. }
  338. void CCtrlSamples::OnActivatePage(LPARAM lParam)
  339. {
  340. if (lParam < 0)
  341. {
  342. int nIns = m_parent.GetInstrumentChange();
  343. if (m_sndFile.GetNumInstruments())
  344. {
  345. if ((nIns > 0) && (!m_modDoc.IsChildSample((INSTRUMENTINDEX)nIns, m_nSample)))
  346. {
  347. SAMPLEINDEX k = m_modDoc.FindInstrumentChild((INSTRUMENTINDEX)nIns);
  348. if (k > 0) lParam = k;
  349. }
  350. } else
  351. {
  352. if (nIns > 0) lParam = nIns;
  353. }
  354. } else if (lParam > 0)
  355. {
  356. if (m_sndFile.GetNumInstruments())
  357. {
  358. INSTRUMENTINDEX k = (INSTRUMENTINDEX)m_parent.GetInstrumentChange();
  359. if (!m_modDoc.IsChildSample(k, (SAMPLEINDEX)lParam))
  360. {
  361. INSTRUMENTINDEX nins = m_modDoc.FindSampleParent((SAMPLEINDEX)lParam);
  362. if(nins != INSTRUMENTINDEX_INVALID)
  363. {
  364. m_parent.InstrumentChanged(nins);
  365. }
  366. }
  367. } else
  368. {
  369. m_parent.InstrumentChanged(static_cast<int>(lParam));
  370. }
  371. }
  372. CChildFrame *pFrame = (CChildFrame *)GetParentFrame();
  373. SAMPLEVIEWSTATE &sampleState = pFrame->GetSampleViewState();
  374. if(sampleState.initialSample != 0)
  375. {
  376. m_nSample = sampleState.initialSample;
  377. sampleState.initialSample = 0;
  378. }
  379. SetCurrentSample((lParam > 0) ? ((SAMPLEINDEX)lParam) : m_nSample);
  380. // Initial Update
  381. if (!m_bInitialized) UpdateView(SampleHint(m_nSample).Info().ModType(), NULL);
  382. if (m_hWndView) PostViewMessage(VIEWMSG_LOADSTATE, (LPARAM)&sampleState);
  383. SwitchToView();
  384. // Combo boxes randomly disappear without this... why?
  385. Invalidate();
  386. }
  387. void CCtrlSamples::OnDeactivatePage()
  388. {
  389. CChildFrame *pFrame = (CChildFrame *)GetParentFrame();
  390. if ((pFrame) && (m_hWndView)) SendViewMessage(VIEWMSG_SAVESTATE, (LPARAM)&pFrame->GetSampleViewState());
  391. m_modDoc.NoteOff(0, true);
  392. }
  393. LRESULT CCtrlSamples::OnModCtrlMsg(WPARAM wParam, LPARAM lParam)
  394. {
  395. switch(wParam)
  396. {
  397. case CTRLMSG_GETCURRENTINSTRUMENT:
  398. return m_nSample;
  399. break;
  400. case CTRLMSG_SMP_PREVINSTRUMENT:
  401. OnPrevInstrument();
  402. break;
  403. case CTRLMSG_SMP_NEXTINSTRUMENT:
  404. OnNextInstrument();
  405. break;
  406. case CTRLMSG_SMP_OPENFILE:
  407. if(lParam)
  408. return OpenSample(*reinterpret_cast<const mpt::PathString *>(lParam));
  409. break;
  410. case CTRLMSG_SMP_SONGDROP:
  411. if(lParam)
  412. {
  413. const auto &dropInfo = *reinterpret_cast<const DRAGONDROP *>(lParam);
  414. if(dropInfo.sndFile)
  415. return OpenSample(*dropInfo.sndFile, static_cast<SAMPLEINDEX>(dropInfo.dropItem)) ? TRUE : FALSE;
  416. }
  417. break;
  418. case CTRLMSG_SMP_SETZOOM:
  419. SetCurrentSample(m_nSample, static_cast<int>(lParam), FALSE);
  420. break;
  421. case CTRLMSG_SETCURRENTINSTRUMENT:
  422. SetCurrentSample((SAMPLEINDEX)lParam, -1, TRUE);
  423. break;
  424. case CTRLMSG_SMP_INITOPL:
  425. OnInitOPLInstrument();
  426. break;
  427. case CTRLMSG_SMP_NEWSAMPLE:
  428. return InsertSample(false) ? 1 : 0;
  429. case IDC_SAMPLE_REVERSE:
  430. OnReverse();
  431. break;
  432. case IDC_SAMPLE_SILENCE:
  433. OnSilence();
  434. break;
  435. case IDC_SAMPLE_INVERT:
  436. OnInvert();
  437. break;
  438. case IDC_SAMPLE_XFADE:
  439. OnXFade();
  440. break;
  441. case IDC_SAMPLE_STEREOSEPARATION:
  442. OnStereoSeparation();
  443. break;
  444. case IDC_SAMPLE_AUTOTUNE:
  445. OnAutotune();
  446. break;
  447. case IDC_SAMPLE_SIGN_UNSIGN:
  448. OnSignUnSign();
  449. break;
  450. case IDC_SAMPLE_DCOFFSET:
  451. RemoveDCOffset(false);
  452. break;
  453. case IDC_SAMPLE_NORMALIZE:
  454. Normalize(false);
  455. break;
  456. case IDC_SAMPLE_AMPLIFY:
  457. OnAmplify();
  458. break;
  459. case IDC_SAMPLE_QUICKFADE:
  460. OnQuickFade();
  461. break;
  462. case IDC_SAMPLE_OPEN:
  463. OnSampleOpen();
  464. break;
  465. case IDC_SAMPLE_SAVEAS:
  466. OnSampleSave();
  467. break;
  468. case IDC_SAMPLE_NEW:
  469. InsertSample(false);
  470. break;
  471. default:
  472. return CModControlDlg::OnModCtrlMsg(wParam, lParam);
  473. }
  474. return 0;
  475. }
  476. BOOL CCtrlSamples::GetToolTipText(UINT uId, LPTSTR pszText)
  477. {
  478. if ((pszText) && (uId))
  479. {
  480. UINT val = GetDlgItemInt(uId);
  481. const TCHAR *s = nullptr;
  482. CommandID cmd = kcNull;
  483. switch(uId)
  484. {
  485. case IDC_SAMPLE_NEW: s = _T("Insert Sample"); cmd = kcSampleNew; break;
  486. case IDC_SAMPLE_OPEN: s = _T("Import Sample"); cmd = kcSampleLoad; break;
  487. case IDC_SAMPLE_SAVEAS: s = _T("Save Sample"); cmd = kcSampleSave; break;
  488. case IDC_SAMPLE_PLAY: s = _T("Play Sample"); break;
  489. case IDC_SAMPLE_NORMALIZE: s = _T("Normalize (hold shift to normalize all samples)"); cmd = kcSampleNormalize; break;
  490. case IDC_SAMPLE_AMPLIFY: s = _T("Amplify"); cmd = kcSampleAmplify; break;
  491. case IDC_SAMPLE_DCOFFSET: s = _T("Remove DC Offset and Normalize (hold shift to process all samples)"); cmd = kcSampleRemoveDCOffset; break;
  492. case IDC_SAMPLE_STEREOSEPARATION: s = _T("Change Stereo Separation / Stereo Width of the sample"); cmd = kcSampleStereoSep; break;
  493. case IDC_SAMPLE_RESAMPLE: s = _T("Resample"); cmd = kcSampleResample; break;
  494. case IDC_SAMPLE_REVERSE: s = _T("Reverse"); cmd = kcSampleReverse; break;
  495. case IDC_SAMPLE_SILENCE: s = _T("Silence"); cmd = kcSampleSilence; break;
  496. case IDC_SAMPLE_INVERT: s = _T("Invert Phase"); cmd = kcSampleInvert; break;
  497. case IDC_SAMPLE_SIGN_UNSIGN: s = _T("Signed/Unsigned Conversion"); cmd = kcSampleSignUnsign; break;
  498. case IDC_SAMPLE_XFADE: s = _T("Crossfade Sample Loops"); cmd = kcSampleXFade; break;
  499. case IDC_SAMPLE_AUTOTUNE: s = _T("Tune the sample to a given note"); cmd = kcSampleAutotune; break;
  500. case IDC_EDIT7:
  501. case IDC_EDIT8:
  502. // Volume to dB
  503. if(IsOPLInstrument())
  504. _tcscpy(pszText, (mpt::tfmt::fix((static_cast<int32>(val) - 64) * 0.75, 2) + _T(" dB")).c_str());
  505. else
  506. _tcscpy(pszText, CModDoc::LinearToDecibels(val, 64.0));
  507. return TRUE;
  508. case IDC_EDIT9:
  509. // Panning
  510. if(m_nSample)
  511. {
  512. const ModSample &sample = m_sndFile.GetSample(m_nSample);
  513. _tcscpy(pszText, CModDoc::PanningToString(sample.nPan, 128));
  514. }
  515. return TRUE;
  516. case IDC_EDIT5:
  517. case IDC_SPIN5:
  518. case IDC_COMBO_BASENOTE:
  519. if(m_nSample)
  520. {
  521. const ModSample &sample = m_sndFile.GetSample(m_nSample);
  522. const auto freqHz = sample.GetSampleRate(m_sndFile.GetType());
  523. if(sample.uFlags[CHN_ADLIB])
  524. {
  525. // Translate to actual note frequency
  526. _tcscpy(pszText, MPT_TFORMAT("{}Hz")(mpt::tfmt::flt(freqHz * (261.625 / 8363.0), 6)).c_str());
  527. return TRUE;
  528. }
  529. if(m_sndFile.UseFinetuneAndTranspose())
  530. {
  531. // Transpose + Finetune to Frequency
  532. _tcscpy(pszText, MPT_TFORMAT("{}Hz")(freqHz).c_str());
  533. return TRUE;
  534. }
  535. }
  536. break;
  537. case IDC_EDIT14:
  538. // Vibrato Sweep
  539. if(!(m_sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_XM)))
  540. {
  541. s = _T("Only available in IT / MPTM / XM format");
  542. break;
  543. } else if(m_nSample)
  544. {
  545. const ModSample &sample = m_sndFile.GetSample(m_nSample);
  546. int ticks = -1;
  547. if(m_sndFile.m_playBehaviour[kITVibratoTremoloPanbrello])
  548. {
  549. if(val > 0)
  550. ticks = Util::muldivr_unsigned(sample.nVibDepth, 256, val);
  551. } else if(m_sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))
  552. {
  553. if(val > 0)
  554. ticks = Util::muldivr_unsigned(sample.nVibDepth, 128, val);
  555. } else
  556. {
  557. ticks = val;
  558. }
  559. if(ticks >= 0)
  560. _stprintf(pszText, _T("%d ticks"), ticks);
  561. else
  562. _tcscpy(pszText, _T("No Vibrato"));
  563. }
  564. return TRUE;
  565. case IDC_EDIT15:
  566. // Vibrato Depth
  567. if(!(m_sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_XM)))
  568. _tcscpy(pszText, _T("Only available in IT / MPTM / XM format"));
  569. else
  570. _stprintf(pszText, _T("%u cents"), Util::muldivr_unsigned(val, 100, 64));
  571. return TRUE;
  572. case IDC_EDIT16:
  573. // Vibrato Rate
  574. if(!(m_sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_XM)))
  575. {
  576. s = _T("Only available in IT / MPTM / XM format");
  577. break;
  578. } else if(val == 0)
  579. {
  580. s = _T("Stopped");
  581. break;
  582. } else
  583. {
  584. const double ticksPerCycle = 256.0 / val;
  585. const uint32 ticksPerBeat = std::max(1u, m_sndFile.m_PlayState.m_nCurrentRowsPerBeat * m_sndFile.m_PlayState.m_nMusicSpeed);
  586. _stprintf(pszText, _T("%.2f beats per cycle (%.2f ticks)"), ticksPerCycle / ticksPerBeat, ticksPerCycle);
  587. }
  588. return TRUE;
  589. case IDC_CHECK1:
  590. case IDC_EDIT3:
  591. case IDC_EDIT4:
  592. case IDC_COMBO2:
  593. if(!(m_sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)))
  594. s = _T("Only available in IT / MPTM format");
  595. break;
  596. case IDC_COMBO3:
  597. if(!(m_sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_XM)))
  598. s = _T("Only available in IT / MPTM / XM format");
  599. break;
  600. case IDC_CHECK2:
  601. s = _T("Keep a reference to the original waveform instead of saving it in the module.");
  602. break;
  603. }
  604. if(s != nullptr)
  605. {
  606. _tcscpy(pszText, s);
  607. if(cmd != kcNull)
  608. {
  609. auto keyText = CMainFrame::GetInputHandler()->m_activeCommandSet->GetKeyTextFromCommand(cmd, 0);
  610. if (!keyText.IsEmpty())
  611. _tcscat(pszText, MPT_TFORMAT(" ({})")(keyText).c_str());
  612. }
  613. return TRUE;
  614. }
  615. }
  616. return FALSE;
  617. }
  618. void CCtrlSamples::UpdateView(UpdateHint hint, CObject *pObj)
  619. {
  620. if(pObj == this) return;
  621. if (hint.GetType()[HINT_MPTOPTIONS])
  622. {
  623. m_ToolBar1.UpdateStyle();
  624. m_ToolBar2.UpdateStyle();
  625. }
  626. const SampleHint sampleHint = hint.ToType<SampleHint>();
  627. FlagSet<HintType> hintType = sampleHint.GetType();
  628. if (!m_bInitialized) hintType.set(HINT_MODTYPE);
  629. if(!hintType[HINT_SMPNAMES | HINT_SAMPLEINFO | HINT_MODTYPE]) return;
  630. const SAMPLEINDEX updateSmp = sampleHint.GetSample();
  631. if(updateSmp != m_nSample && updateSmp != 0 && !hintType[HINT_MODTYPE]) return;
  632. const CModSpecifications &specs = m_sndFile.GetModSpecifications();
  633. const bool isOPL = IsOPLInstrument();
  634. LockControls();
  635. // Updating Ranges
  636. if(hintType[HINT_MODTYPE])
  637. {
  638. // Limit text fields
  639. m_EditName.SetLimitText(specs.sampleNameLengthMax);
  640. m_EditFileName.SetLimitText(specs.sampleFilenameLengthMax);
  641. // Loop Type
  642. m_ComboLoopType.ResetContent();
  643. m_ComboLoopType.AddString(_T("Off"));
  644. m_ComboLoopType.AddString(_T("On"));
  645. // Sustain Loop Type
  646. m_ComboSustainType.ResetContent();
  647. m_ComboSustainType.AddString(_T("Off"));
  648. m_ComboSustainType.AddString(_T("On"));
  649. // Bidirectional Loops
  650. if (m_sndFile.GetType() & (MOD_TYPE_XM|MOD_TYPE_IT|MOD_TYPE_MPT))
  651. {
  652. m_ComboLoopType.AddString(_T("Bidi"));
  653. m_ComboSustainType.AddString(_T("Bidi"));
  654. }
  655. // Loop Start
  656. m_SpinLoopStart.SetRange(-1, 1);
  657. m_SpinLoopStart.SetPos(0);
  658. // Loop End
  659. m_SpinLoopEnd.SetRange(-1, 1);
  660. m_SpinLoopEnd.SetPos(0);
  661. // Sustain Loop Start
  662. m_SpinSustainStart.SetRange(-1, 1);
  663. m_SpinSustainStart.SetPos(0);
  664. // Sustain Loop End
  665. m_SpinSustainEnd.SetRange(-1, 1);
  666. m_SpinSustainEnd.SetPos(0);
  667. // Finetune / C-5 Speed / BaseNote
  668. BOOL b = m_sndFile.UseFinetuneAndTranspose() ? FALSE : TRUE;
  669. SetDlgItemText(IDC_TEXT7, (b) ? _T("Freq. (Hz)") : _T("Finetune"));
  670. m_SpinFineTune.SetRange(-1, 1);
  671. m_EditFileName.EnableWindow(b);
  672. // AutoVibrato
  673. b = (m_sndFile.GetType() & (MOD_TYPE_XM|MOD_TYPE_IT|MOD_TYPE_MPT)) ? TRUE : FALSE;
  674. m_ComboAutoVib.EnableWindow(b);
  675. m_SpinVibSweep.EnableWindow(b);
  676. m_SpinVibDepth.EnableWindow(b);
  677. m_SpinVibRate.EnableWindow(b);
  678. m_EditVibSweep.EnableWindow(b);
  679. m_EditVibDepth.EnableWindow(b);
  680. m_EditVibRate.EnableWindow(b);
  681. m_SpinVibSweep.SetRange(0, 255);
  682. if(m_sndFile.GetType() & MOD_TYPE_XM)
  683. {
  684. m_SpinVibDepth.SetRange(0, 15);
  685. m_SpinVibRate.SetRange(0, 63);
  686. } else
  687. {
  688. m_SpinVibDepth.SetRange(0, 32);
  689. m_SpinVibRate.SetRange(0, 64);
  690. }
  691. // Global Volume
  692. b = (m_sndFile.GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT)) ? TRUE : FALSE;
  693. m_EditGlobalVol.EnableWindow(b);
  694. m_SpinGlobalVol.EnableWindow(b);
  695. // Panning
  696. b = (m_sndFile.GetType() & (MOD_TYPE_XM|MOD_TYPE_IT|MOD_TYPE_MPT)) ? TRUE : FALSE;
  697. m_CheckPanning.EnableWindow(b && !(m_sndFile.GetType() & MOD_TYPE_XM));
  698. m_EditPanning.EnableWindow(b);
  699. m_SpinPanning.EnableWindow(b);
  700. m_SpinPanning.SetRange(0, (m_sndFile.GetType() == MOD_TYPE_XM) ? 255 : 64);
  701. b = (m_sndFile.GetType() & MOD_TYPE_MOD) ? FALSE : TRUE;
  702. m_CbnBaseNote.EnableWindow(b);
  703. }
  704. // Updating Values
  705. if (hintType[HINT_MODTYPE | HINT_SAMPLEINFO])
  706. {
  707. if(m_nSample > m_sndFile.GetNumSamples())
  708. {
  709. SetCurrentSample(m_sndFile.GetNumSamples());
  710. }
  711. const ModSample &sample = m_sndFile.GetSample(m_nSample);
  712. CString s;
  713. DWORD d;
  714. m_SpinSample.SetRange(1, m_sndFile.GetNumSamples());
  715. m_SpinSample.Invalidate(FALSE); // In case the spin button was previously disabled
  716. // Length / Type
  717. if(isOPL)
  718. s = _T("OPL instrument");
  719. else
  720. s = MPT_CFORMAT("{}-bit {}, len: {}")(sample.GetElementarySampleSize() * 8, CString(sample.uFlags[CHN_STEREO] ? _T("stereo") : _T("mono")), mpt::cfmt::dec(3, ',', sample.nLength));
  721. SetDlgItemText(IDC_TEXT5, s);
  722. // File Name
  723. s = mpt::ToCString(m_sndFile.GetCharsetInternal(), sample.filename);
  724. if (specs.sampleFilenameLengthMax == 0) s.Empty();
  725. SetDlgItemText(IDC_SAMPLE_FILENAME, s);
  726. // Volume
  727. if(sample.uFlags[SMP_NODEFAULTVOLUME])
  728. SetDlgItemText(IDC_EDIT7, _T("none"));
  729. else
  730. SetDlgItemInt(IDC_EDIT7, sample.nVolume / 4u);
  731. // Global Volume
  732. SetDlgItemInt(IDC_EDIT8, sample.nGlobalVol);
  733. // Panning
  734. CheckDlgButton(IDC_CHECK1, (sample.uFlags[CHN_PANNING]) ? BST_CHECKED : BST_UNCHECKED);
  735. if (m_sndFile.GetType() == MOD_TYPE_XM)
  736. SetDlgItemInt(IDC_EDIT9, sample.nPan); //displayed panning with XM is 0-256, just like MPT's internal engine
  737. else
  738. SetDlgItemInt(IDC_EDIT9, sample.nPan / 4u); //displayed panning with anything but XM is 0-64 so we divide by 4
  739. // FineTune / C-4 Speed / BaseNote
  740. int transp = 0;
  741. if (!m_sndFile.UseFinetuneAndTranspose())
  742. {
  743. s = mpt::cfmt::val(sample.nC5Speed);
  744. m_EditFineTune.SetWindowText(s);
  745. if(sample.nC5Speed != 0)
  746. transp = ModSample::FrequencyToTranspose(sample.nC5Speed).first;
  747. } else
  748. {
  749. int ftune = ((int)sample.nFineTune);
  750. // MOD finetune range -8 to 7 translates to -128 to 112
  751. if(m_sndFile.GetType() & MOD_TYPE_MOD) ftune >>= 4;
  752. SetDlgItemInt(IDC_EDIT5, ftune);
  753. transp = (int)sample.RelativeTone;
  754. }
  755. int basenote = (NOTE_MIDDLEC - NOTE_MIN) + transp;
  756. Limit(basenote, BASENOTE_MIN, BASENOTE_MAX);
  757. basenote -= BASENOTE_MIN;
  758. if (basenote != m_CbnBaseNote.GetCurSel()) m_CbnBaseNote.SetCurSel(basenote);
  759. // Auto vibrato
  760. // Ramp up and ramp down are swapped in XM - probably because they ramp up the *period* instead of *frequency*.
  761. const VibratoType rampUp = m_sndFile.GetType() == MOD_TYPE_XM ? VIB_RAMP_DOWN : VIB_RAMP_UP;
  762. const VibratoType rampDown = m_sndFile.GetType() == MOD_TYPE_XM ? VIB_RAMP_UP : VIB_RAMP_DOWN;
  763. m_ComboAutoVib.ResetContent();
  764. m_ComboAutoVib.SetItemData(m_ComboAutoVib.AddString(_T("Sine")), VIB_SINE);
  765. m_ComboAutoVib.SetItemData(m_ComboAutoVib.AddString(_T("Square")), VIB_SQUARE);
  766. if(m_sndFile.GetType() != MOD_TYPE_IT || sample.nVibType == VIB_RAMP_UP)
  767. m_ComboAutoVib.SetItemData(m_ComboAutoVib.AddString(_T("Ramp Up")), rampUp);
  768. m_ComboAutoVib.SetItemData(m_ComboAutoVib.AddString(_T("Ramp Down")), rampDown);
  769. if(m_sndFile.GetType() != MOD_TYPE_XM || sample.nVibType == VIB_RANDOM)
  770. m_ComboAutoVib.SetItemData(m_ComboAutoVib.AddString(_T("Random")), VIB_RANDOM);
  771. for(int i = 0; i < m_ComboAutoVib.GetCount(); i++)
  772. {
  773. if(m_ComboAutoVib.GetItemData(i) == sample.nVibType)
  774. {
  775. m_ComboAutoVib.SetCurSel(i);
  776. break;
  777. }
  778. }
  779. SetDlgItemInt(IDC_EDIT14, sample.nVibSweep);
  780. SetDlgItemInt(IDC_EDIT15, sample.nVibDepth);
  781. SetDlgItemInt(IDC_EDIT16, sample.nVibRate);
  782. // Loop
  783. d = 0;
  784. if (sample.uFlags[CHN_LOOP]) d = sample.uFlags[CHN_PINGPONGLOOP] ? 2 : 1;
  785. if (sample.uFlags[CHN_REVERSE]) d |= 4;
  786. m_ComboLoopType.SetCurSel(d);
  787. s = mpt::cfmt::val(sample.nLoopStart);
  788. m_EditLoopStart.SetWindowText(s);
  789. s = mpt::cfmt::val(sample.nLoopEnd);
  790. m_EditLoopEnd.SetWindowText(s);
  791. // Sustain Loop
  792. d = 0;
  793. if (sample.uFlags[CHN_SUSTAINLOOP]) d = sample.uFlags[CHN_PINGPONGSUSTAIN] ? 2 : 1;
  794. m_ComboSustainType.SetCurSel(d);
  795. s = mpt::cfmt::val(sample.nSustainStart);
  796. m_EditSustainStart.SetWindowText(s);
  797. s = mpt::cfmt::val(sample.nSustainEnd);
  798. m_EditSustainEnd.SetWindowText(s);
  799. // Disable certain buttons for OPL instruments
  800. BOOL b = isOPL ? FALSE : TRUE;
  801. static constexpr int sampleButtons[] =
  802. {
  803. IDC_SAMPLE_NORMALIZE, IDC_SAMPLE_AMPLIFY,
  804. IDC_SAMPLE_DCOFFSET, IDC_SAMPLE_STEREOSEPARATION,
  805. IDC_SAMPLE_RESAMPLE, IDC_SAMPLE_REVERSE,
  806. IDC_SAMPLE_SILENCE, IDC_SAMPLE_INVERT,
  807. IDC_SAMPLE_SIGN_UNSIGN, IDC_SAMPLE_XFADE,
  808. };
  809. for(auto btn : sampleButtons)
  810. {
  811. m_ToolBar2.EnableButton(btn, b);
  812. }
  813. m_ComboLoopType.EnableWindow(b);
  814. m_SpinLoopStart.EnableWindow(b);
  815. m_SpinLoopEnd.EnableWindow(b);
  816. m_EditLoopStart.EnableWindow(b);
  817. m_EditLoopEnd.EnableWindow(b);
  818. const bool hasSustainLoop = !isOPL && ((m_sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (m_nSample <= m_sndFile.GetNumSamples() && m_sndFile.GetSample(m_nSample).uFlags[CHN_SUSTAINLOOP]));
  819. b = hasSustainLoop ? TRUE : FALSE;
  820. m_ComboSustainType.EnableWindow(b);
  821. m_SpinSustainStart.EnableWindow(b);
  822. m_SpinSustainEnd.EnableWindow(b);
  823. m_EditSustainStart.EnableWindow(b);
  824. m_EditSustainEnd.EnableWindow(b);
  825. }
  826. if(hintType[HINT_MODTYPE | HINT_SAMPLEINFO | HINT_SMPNAMES])
  827. {
  828. // Name
  829. SetDlgItemText(IDC_SAMPLE_NAME, mpt::ToWin(m_sndFile.GetCharsetInternal(), m_sndFile.m_szNames[m_nSample]).c_str());
  830. CheckDlgButton(IDC_CHECK2, m_sndFile.GetSample(m_nSample).uFlags[SMP_KEEPONDISK] ? BST_CHECKED : BST_UNCHECKED);
  831. GetDlgItem(IDC_CHECK2)->EnableWindow((m_sndFile.SampleHasPath(m_nSample) && m_sndFile.GetType() == MOD_TYPE_MPT) ? TRUE : FALSE);
  832. }
  833. if (!m_bInitialized)
  834. {
  835. // First update
  836. m_bInitialized = TRUE;
  837. UnlockControls();
  838. }
  839. m_ComboLoopType.Invalidate(FALSE);
  840. m_ComboSustainType.Invalidate(FALSE);
  841. m_ComboAutoVib.Invalidate(FALSE);
  842. UnlockControls();
  843. }
  844. // updateAll: Update all views including this one. Otherwise, only update update other views.
  845. void CCtrlSamples::SetModified(SampleHint hint, bool updateAll, bool waveformModified)
  846. {
  847. m_modDoc.SetModified();
  848. if(waveformModified)
  849. {
  850. // Update on-disk sample status in tree
  851. ModSample &sample = m_sndFile.GetSample(m_nSample);
  852. if(sample.uFlags[SMP_KEEPONDISK] && !sample.uFlags[SMP_MODIFIED]) hint.Names();
  853. sample.uFlags.set(SMP_MODIFIED);
  854. }
  855. m_modDoc.UpdateAllViews(nullptr, hint.SetData(m_nSample), updateAll ? nullptr : this);
  856. }
  857. void CCtrlSamples::PrepareUndo(const char *description, sampleUndoTypes type, SmpLength start, SmpLength end)
  858. {
  859. m_startedEdit = true;
  860. m_modDoc.GetSampleUndo().PrepareUndo(m_nSample, type, description, start, end);
  861. }
  862. bool CCtrlSamples::OpenSample(const mpt::PathString &fileName, FlagSet<OpenSampleTypes> types)
  863. {
  864. BeginWaitCursor();
  865. InputFile f(fileName, TrackerSettings::Instance().MiscCacheCompleteFileBeforeLoading);
  866. if(!f.IsValid())
  867. {
  868. EndWaitCursor();
  869. return false;
  870. }
  871. FileReader file = GetFileReader(f);
  872. if(!file.IsValid())
  873. {
  874. EndWaitCursor();
  875. return false;
  876. }
  877. PrepareUndo("Replace", sundo_replace);
  878. const auto parentIns = GetParentInstrumentWithSameName();
  879. bool bOk = false;
  880. if(types[OpenSampleKnown])
  881. {
  882. bOk = m_sndFile.ReadSampleFromFile(m_nSample, file, TrackerSettings::Instance().m_MayNormalizeSamplesOnLoad);
  883. if(!bOk)
  884. {
  885. // Try loading as module
  886. bOk = CMainFrame::GetMainFrame()->SetTreeSoundfile(file);
  887. if(bOk)
  888. {
  889. m_modDoc.GetSampleUndo().RemoveLastUndoStep(m_nSample);
  890. return true;
  891. }
  892. }
  893. }
  894. ModSample &sample = m_sndFile.GetSample(m_nSample);
  895. if(!bOk && types[OpenSampleRaw])
  896. {
  897. CRawSampleDlg dlg(file, this);
  898. EndWaitCursor();
  899. if(m_rememberRawFormat || dlg.DoModal() == IDOK)
  900. {
  901. SampleIO sampleIO = dlg.GetSampleFormat();
  902. m_rememberRawFormat = m_rememberRawFormat || dlg.GetRemeberFormat();
  903. BeginWaitCursor();
  904. file.Seek(dlg.GetOffset());
  905. m_sndFile.DestroySampleThreadsafe(m_nSample);
  906. const auto bytesPerSample = sampleIO.GetNumChannels() * sampleIO.GetBitDepth() / 8u;
  907. sample.nLength = mpt::saturate_cast<SmpLength>(file.BytesLeft() / bytesPerSample);
  908. if(TrackerSettings::Instance().m_MayNormalizeSamplesOnLoad)
  909. {
  910. sampleIO.MayNormalize();
  911. }
  912. if(sampleIO.ReadSample(sample, file))
  913. {
  914. bOk = true;
  915. sample.nGlobalVol = 64;
  916. sample.nVolume = 256;
  917. sample.nPan = 128;
  918. sample.uFlags.reset(CHN_LOOP | CHN_SUSTAINLOOP | SMP_MODIFIED);
  919. sample.filename = "";
  920. m_sndFile.m_szNames[m_nSample] = "";
  921. if(!sample.nC5Speed) sample.nC5Speed = 22050;
  922. sample.PrecomputeLoops(m_sndFile, false);
  923. } else
  924. {
  925. m_modDoc.GetSampleUndo().Undo(m_nSample);
  926. }
  927. } else
  928. {
  929. m_modDoc.GetSampleUndo().RemoveLastUndoStep(m_nSample);
  930. }
  931. } else
  932. {
  933. m_sndFile.SetSamplePath(m_nSample, fileName);
  934. }
  935. EndWaitCursor();
  936. if (bOk)
  937. {
  938. TrackerSettings::Instance().PathSamples.SetWorkingDir(fileName, true);
  939. if(sample.filename.empty())
  940. {
  941. mpt::PathString name, ext;
  942. fileName.SplitPath(nullptr, nullptr, &name, &ext);
  943. if(m_sndFile.m_szNames[m_nSample].empty()) m_sndFile.m_szNames[m_nSample] = name.ToLocale();
  944. if(name.AsNative().length() < 9) name += ext;
  945. sample.filename = name.ToLocale();
  946. }
  947. if ((m_sndFile.GetType() & MOD_TYPE_XM) && !sample.uFlags[CHN_PANNING])
  948. {
  949. sample.nPan = 128;
  950. sample.uFlags.set(CHN_PANNING);
  951. }
  952. SetModified(SampleHint().Info().Data().Names(), true, false);
  953. sample.uFlags.reset(SMP_KEEPONDISK);
  954. if(parentIns <= m_sndFile.GetNumInstruments())
  955. {
  956. if(auto instr = m_sndFile.Instruments[parentIns]; instr != nullptr)
  957. {
  958. m_modDoc.GetInstrumentUndo().PrepareUndo(parentIns, "Set Name");
  959. instr->name = m_sndFile.m_szNames[m_nSample];
  960. m_modDoc.UpdateAllViews(nullptr, InstrumentHint(parentIns).Names(), this);
  961. }
  962. }
  963. }
  964. return true;
  965. }
  966. bool CCtrlSamples::OpenSample(const CSoundFile &sndFile, SAMPLEINDEX nSample)
  967. {
  968. if(!nSample || nSample > sndFile.GetNumSamples()) return false;
  969. BeginWaitCursor();
  970. PrepareUndo("Replace", sundo_replace);
  971. const auto parentIns = GetParentInstrumentWithSameName();
  972. if(m_sndFile.ReadSampleFromSong(m_nSample, sndFile, nSample))
  973. {
  974. SetModified(SampleHint().Info().Data().Names(), true, false);
  975. if(parentIns <= m_sndFile.GetNumInstruments())
  976. {
  977. if(auto instr = m_sndFile.Instruments[parentIns]; instr != nullptr)
  978. {
  979. m_modDoc.GetInstrumentUndo().PrepareUndo(parentIns, "Set Name");
  980. instr->name = m_sndFile.m_szNames[m_nSample];
  981. m_modDoc.UpdateAllViews(nullptr, InstrumentHint(parentIns).Names(), this);
  982. }
  983. }
  984. } else
  985. {
  986. m_modDoc.GetSampleUndo().RemoveLastUndoStep(m_nSample);
  987. }
  988. EndWaitCursor();
  989. return true;
  990. }
  991. //////////////////////////////////////////////////////////////////////////////////
  992. // CCtrlSamples messages
  993. void CCtrlSamples::OnSampleChanged()
  994. {
  995. if(!IsLocked())
  996. {
  997. SAMPLEINDEX n = (SAMPLEINDEX)GetDlgItemInt(IDC_EDIT_SAMPLE);
  998. if ((n > 0) && (n <= m_sndFile.GetNumSamples()) && (n != m_nSample))
  999. {
  1000. SetCurrentSample(n, -1, FALSE);
  1001. m_parent.SampleChanged(m_nSample);
  1002. }
  1003. }
  1004. }
  1005. void CCtrlSamples::OnZoomChanged()
  1006. {
  1007. if (!IsLocked()) SetCurrentSample(m_nSample);
  1008. SwitchToView();
  1009. }
  1010. void CCtrlSamples::OnTbnDropDownToolBar(NMHDR *pNMHDR, LRESULT *pResult)
  1011. {
  1012. CInputHandler *ih = CMainFrame::GetInputHandler();
  1013. NMTOOLBAR *pToolBar = reinterpret_cast<NMTOOLBAR *>(pNMHDR);
  1014. ClientToScreen(&(pToolBar->rcButton)); // TrackPopupMenu uses screen coords
  1015. const int offset = Util::ScalePixels(4, m_hWnd); // Compared to the main toolbar, the offset seems to be a bit wrong here...?
  1016. int x = pToolBar->rcButton.left + offset, y = pToolBar->rcButton.bottom + offset;
  1017. CMenu menu;
  1018. switch(pToolBar->iItem)
  1019. {
  1020. case IDC_SAMPLE_NEW:
  1021. {
  1022. menu.CreatePopupMenu();
  1023. menu.AppendMenu(MF_STRING, IDC_SAMPLE_DUPLICATE, ih->GetKeyTextFromCommand(kcSampleDuplicate, m_sndFile.GetSample(m_nSample).uFlags[CHN_ADLIB] ? _T("&Duplicate Instrument") : _T("&Duplicate Sample")));
  1024. menu.AppendMenu(MF_STRING | (m_sndFile.SupportsOPL() ? 0 : MF_DISABLED), IDC_SAMPLE_INITOPL, ih->GetKeyTextFromCommand(kcSampleInitializeOPL, _T("Initialize &OPL Instrument")));
  1025. menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, this);
  1026. menu.DestroyMenu();
  1027. }
  1028. break;
  1029. case IDC_SAMPLE_OPEN:
  1030. {
  1031. menu.CreatePopupMenu();
  1032. menu.AppendMenu(MF_STRING, IDC_SAMPLE_OPENKNOWN, ih->GetKeyTextFromCommand(kcSampleLoad, _T("Import &Sample...")));
  1033. menu.AppendMenu(MF_STRING, IDC_SAMPLE_OPENRAW, ih->GetKeyTextFromCommand(kcSampleLoadRaw, _T("Import &Raw Sample...")));
  1034. menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, this);
  1035. menu.DestroyMenu();
  1036. }
  1037. break;
  1038. case IDC_SAMPLE_SAVEAS:
  1039. {
  1040. menu.CreatePopupMenu();
  1041. menu.AppendMenu(MF_STRING, IDC_SAVE_ALL, _T("Save &All..."));
  1042. menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, this);
  1043. menu.DestroyMenu();
  1044. }
  1045. break;
  1046. }
  1047. *pResult = 0;
  1048. }
  1049. void CCtrlSamples::OnSampleNew()
  1050. {
  1051. InsertSample(CMainFrame::GetInputHandler()->ShiftPressed());
  1052. SwitchToView();
  1053. }
  1054. bool CCtrlSamples::InsertSample(bool duplicate, int8 *confirm)
  1055. {
  1056. const SAMPLEINDEX smp = m_modDoc.InsertSample();
  1057. if(smp != SAMPLEINDEX_INVALID)
  1058. {
  1059. const SAMPLEINDEX oldSmp = m_nSample;
  1060. CSoundFile &sndFile = m_modDoc.GetSoundFile();
  1061. SetCurrentSample(smp);
  1062. if(duplicate && oldSmp >= 1 && oldSmp <= sndFile.GetNumSamples())
  1063. {
  1064. m_modDoc.GetSampleUndo().PrepareUndo(smp, sundo_replace, "Duplicate");
  1065. sndFile.ReadSampleFromSong(smp, sndFile, oldSmp);
  1066. }
  1067. m_modDoc.UpdateAllViews(nullptr, SampleHint(smp).Info().Data().Names());
  1068. if(m_modDoc.GetNumInstruments() > 0 && m_modDoc.FindSampleParent(smp) == INSTRUMENTINDEX_INVALID)
  1069. {
  1070. bool insertInstrument;
  1071. if(confirm == nullptr || *confirm == -1)
  1072. {
  1073. insertInstrument = Reporting::Confirm("This sample is not used by any instrument. Do you want to create a new instrument using this sample?") == cnfYes;
  1074. if(confirm != nullptr) *confirm = insertInstrument;
  1075. } else
  1076. {
  1077. insertInstrument = (*confirm) != 0;
  1078. }
  1079. if(insertInstrument)
  1080. {
  1081. INSTRUMENTINDEX nins = m_modDoc.InsertInstrument(smp);
  1082. m_modDoc.UpdateAllViews(nullptr, InstrumentHint(nins).Info().Envelope().Names());
  1083. m_parent.InstrumentChanged(nins);
  1084. }
  1085. }
  1086. }
  1087. return (smp != SAMPLEINDEX_INVALID);
  1088. }
  1089. static constexpr std::pair<const mpt::uchar *, const mpt::uchar *> SampleFormats[]
  1090. {
  1091. { UL_("Wave Files (*.wav)"), UL_("*.wav") },
  1092. #ifdef MPT_WITH_FLAC
  1093. { UL_("FLAC Files (*.flac,*.oga)"), UL_("*.flac;*.oga") },
  1094. #endif // MPT_WITH_FLAC
  1095. #if defined(MPT_WITH_OPUSFILE)
  1096. { UL_("Opus Files (*.opus,*.oga)"), UL_("*.opus;*.oga") },
  1097. #endif // MPT_WITH_OPUSFILE
  1098. #if defined(MPT_WITH_VORBISFILE) || defined(MPT_WITH_STBVORBIS)
  1099. { UL_("Ogg Vorbis Files (*.ogg,*.oga)"), UL_("*.ogg;*.oga") },
  1100. #endif // VORBIS
  1101. #if defined(MPT_ENABLE_MP3_SAMPLES)
  1102. { UL_("MPEG Files (*.mp1,*.mp2,*.mp3)"), UL_("*.mp1;*.mp2;*.mp3") },
  1103. #endif // MPT_ENABLE_MP3_SAMPLES
  1104. { UL_("XI Samples (*.xi)"), UL_("*.xi") },
  1105. { UL_("Impulse Tracker Samples (*.its)"), UL_("*.its") },
  1106. { UL_("Scream Tracker Samples (*.s3i,*.smp)"), UL_("*.s3i;*.smp") },
  1107. { UL_("OPL Instruments (*.sb0,*.sb2,*.sbi)"), UL_("*.sb0;*.sb2;*.sbi") },
  1108. { UL_("GF1 Patches (*.pat)"), UL_("*.pat") },
  1109. { UL_("Wave64 Files (*.w64)"), UL_("*.w64") },
  1110. { UL_("CAF Files (*.wav)"), UL_("*.caf") },
  1111. { UL_("AIFF Files (*.aiff,*.8svx)"), UL_("*.aif;*.aiff;*.iff;*.8sv;*.8svx;*.svx") },
  1112. { UL_("Sun Audio (*.au,*.snd)"), UL_("*.au;*.snd") },
  1113. { UL_("SNES BRR Files (*.brr)"), UL_("*.brr") },
  1114. };
  1115. static mpt::ustring ConstructFileFilter(bool includeRaw)
  1116. {
  1117. mpt::ustring s = U_("All Samples (*.wav,*.flac,*.xi,*.its,*.s3i,*.sbi,...)|");
  1118. bool first = true;
  1119. for(const auto &[name, exts] : SampleFormats)
  1120. {
  1121. if(!first)
  1122. s += U_(";");
  1123. else
  1124. first = false;
  1125. s += exts;
  1126. }
  1127. #if defined(MPT_WITH_MEDIAFOUNDATION)
  1128. std::vector<FileType> mediaFoundationTypes = CSoundFile::GetMediaFoundationFileTypes();
  1129. s += ToFilterOnlyString(mediaFoundationTypes, true).ToUnicode();
  1130. #endif
  1131. if(includeRaw)
  1132. {
  1133. s += U_(";*.raw;*.snd;*.pcm;*.sam");
  1134. }
  1135. s += U_("|");
  1136. for(const auto &[name, exts] : SampleFormats)
  1137. {
  1138. s += name + U_("|");
  1139. s += exts + U_("|");
  1140. }
  1141. #if defined(MPT_WITH_MEDIAFOUNDATION)
  1142. s += ToFilterString(mediaFoundationTypes, FileTypeFormatShowExtensions).ToUnicode();
  1143. #endif
  1144. if(includeRaw)
  1145. {
  1146. s += U_("Raw Samples (*.raw,*.snd,*.pcm,*.sam)|*.raw;*.snd;*.pcm;*.sam|");
  1147. }
  1148. s += U_("All Files (*.*)|*.*||");
  1149. return s;
  1150. }
  1151. void CCtrlSamples::OnSampleOpen()
  1152. {
  1153. static int nLastIndex = 0;
  1154. std::vector<FileType> mediaFoundationTypes = CSoundFile::GetMediaFoundationFileTypes();
  1155. FileDialog dlg = OpenFileDialog()
  1156. .AllowMultiSelect()
  1157. .EnableAudioPreview()
  1158. .ExtensionFilter(ConstructFileFilter(true))
  1159. .WorkingDirectory(TrackerSettings::Instance().PathSamples.GetWorkingDir())
  1160. .FilterIndex(&nLastIndex);
  1161. if(!dlg.Show(this)) return;
  1162. TrackerSettings::Instance().PathSamples.SetWorkingDir(dlg.GetWorkingDirectory());
  1163. OpenSamples(dlg.GetFilenames(), OpenSampleKnown | OpenSampleRaw);
  1164. SwitchToView();
  1165. }
  1166. void CCtrlSamples::OnSampleOpenKnown()
  1167. {
  1168. static int nLastIndex = 0;
  1169. std::vector<FileType> mediaFoundationTypes = CSoundFile::GetMediaFoundationFileTypes();
  1170. FileDialog dlg = OpenFileDialog()
  1171. .AllowMultiSelect()
  1172. .EnableAudioPreview()
  1173. .ExtensionFilter(ConstructFileFilter(false))
  1174. .WorkingDirectory(TrackerSettings::Instance().PathSamples.GetWorkingDir())
  1175. .FilterIndex(&nLastIndex);
  1176. if(!dlg.Show(this)) return;
  1177. TrackerSettings::Instance().PathSamples.SetWorkingDir(dlg.GetWorkingDirectory());
  1178. OpenSamples(dlg.GetFilenames(), OpenSampleKnown);
  1179. }
  1180. void CCtrlSamples::OnSampleOpenRaw()
  1181. {
  1182. static int nLastIndex = 0;
  1183. FileDialog dlg = OpenFileDialog()
  1184. .AllowMultiSelect()
  1185. .EnableAudioPreview()
  1186. .ExtensionFilter("Raw Samples (*.raw,*.snd,*.pcm,*.sam)|*.raw;*.snd;*.pcm;*.sam|"
  1187. "All Files (*.*)|*.*||")
  1188. .WorkingDirectory(TrackerSettings::Instance().PathSamples.GetWorkingDir())
  1189. .FilterIndex(&nLastIndex);
  1190. if(!dlg.Show(this)) return;
  1191. TrackerSettings::Instance().PathSamples.SetWorkingDir(dlg.GetWorkingDirectory());
  1192. OpenSamples(dlg.GetFilenames(), OpenSampleRaw);
  1193. }
  1194. void CCtrlSamples::OpenSamples(const std::vector<mpt::PathString> &files, FlagSet<OpenSampleTypes> types)
  1195. {
  1196. int8 confirm = -1;
  1197. bool first = true;
  1198. for(const auto &file : files)
  1199. {
  1200. // If loading multiple samples, create new slots for them
  1201. if(!first)
  1202. {
  1203. if(!InsertSample(false, &confirm))
  1204. break;
  1205. }
  1206. if(OpenSample(file, types))
  1207. first = false;
  1208. else
  1209. ErrorBox(IDS_ERR_FILEOPEN, this);
  1210. }
  1211. SwitchToView();
  1212. }
  1213. void CCtrlSamples::OnSampleSave()
  1214. {
  1215. SaveSample(CMainFrame::GetInputHandler()->ShiftPressed());
  1216. }
  1217. void CCtrlSamples::SaveSample(bool doBatchSave)
  1218. {
  1219. mpt::PathString fileName, defaultPath = TrackerSettings::Instance().PathSamples.GetWorkingDir();
  1220. SampleEditorDefaultFormat defaultFormat = TrackerSettings::Instance().m_defaultSampleFormat;
  1221. bool hasAdlib = false;
  1222. if(!doBatchSave)
  1223. {
  1224. // Save this sample
  1225. const ModSample &sample = m_sndFile.GetSample(m_nSample);
  1226. if((!m_nSample) || (!sample.HasSampleData()))
  1227. {
  1228. SwitchToView();
  1229. return;
  1230. }
  1231. if(m_sndFile.SampleHasPath(m_nSample))
  1232. {
  1233. // For on-disk samples, propose their original filename and location
  1234. auto path = m_sndFile.GetSamplePath(m_nSample);
  1235. fileName = path.GetFullFileName();
  1236. defaultPath = path.GetPath();
  1237. }
  1238. if(fileName.empty()) fileName = mpt::PathString::FromLocale(sample.filename);
  1239. if(fileName.empty()) fileName = mpt::PathString::FromLocale(m_sndFile.m_szNames[m_nSample]);
  1240. if(fileName.empty()) fileName = P_("untitled");
  1241. const mpt::PathString ext = fileName.GetFileExt();
  1242. if(!mpt::PathString::CompareNoCase(ext, P_(".flac"))) defaultFormat = dfFLAC;
  1243. else if(!mpt::PathString::CompareNoCase(ext, P_(".wav"))) defaultFormat = dfWAV;
  1244. else if(!mpt::PathString::CompareNoCase(ext, P_(".s3i"))) defaultFormat = dfS3I;
  1245. hasAdlib = sample.uFlags[CHN_ADLIB];
  1246. } else
  1247. {
  1248. // Save all samples
  1249. fileName = m_sndFile.GetpModDoc()->GetPathNameMpt().GetFileName();
  1250. if(fileName.empty()) fileName = P_("untitled");
  1251. fileName += P_(" - %sample_number% - ");
  1252. if(m_sndFile.GetModSpecifications().sampleFilenameLengthMax == 0)
  1253. fileName += P_("%sample_name%");
  1254. else
  1255. fileName += P_("%sample_filename%");
  1256. }
  1257. SanitizeFilename(fileName);
  1258. int filter;
  1259. switch(defaultFormat)
  1260. {
  1261. case dfWAV:
  1262. filter = 1;
  1263. break;
  1264. case dfFLAC:
  1265. default:
  1266. filter = 2;
  1267. break;
  1268. case dfS3I:
  1269. filter = 3;
  1270. break;
  1271. case dfRAW:
  1272. filter = 4;
  1273. break;
  1274. }
  1275. // Do we have to use a format that can save OPL instruments?
  1276. if(hasAdlib)
  1277. filter = 3;
  1278. FileDialog dlg = SaveFileDialog()
  1279. .DefaultExtension(ToSettingValue(defaultFormat).as<mpt::ustring>())
  1280. .DefaultFilename(fileName)
  1281. .ExtensionFilter("Wave File (*.wav)|*.wav|"
  1282. "FLAC File (*.flac)|*.flac|"
  1283. "S3I Scream Tracker 3 Instrument (*.s3i)|*.s3i|"
  1284. "RAW Audio (*.raw)|*.raw||")
  1285. .WorkingDirectory(defaultPath)
  1286. .FilterIndex(&filter);
  1287. if(!dlg.Show(this)) return;
  1288. BeginWaitCursor();
  1289. const auto saveFormat = FromSettingValue<SampleEditorDefaultFormat>(dlg.GetExtension().ToUnicode());
  1290. SAMPLEINDEX minSmp = m_nSample, maxSmp = m_nSample;
  1291. if(doBatchSave)
  1292. {
  1293. minSmp = 1;
  1294. maxSmp = m_sndFile.GetNumSamples();
  1295. }
  1296. const auto numberFmt = mpt::FormatSpec().Dec().FillNul().Width(1 + static_cast<int>(std::log10(maxSmp)));
  1297. bool ok = false;
  1298. CString sampleName, sampleFilename;
  1299. for(SAMPLEINDEX smp = minSmp; smp <= maxSmp; smp++)
  1300. {
  1301. ModSample &sample = m_sndFile.GetSample(smp);
  1302. if(sample.HasSampleData())
  1303. {
  1304. const bool isAdlib = sample.uFlags[CHN_ADLIB];
  1305. fileName = dlg.GetFirstFile();
  1306. if(doBatchSave)
  1307. {
  1308. sampleName = mpt::ToCString(m_sndFile.GetCharsetInternal(), (!m_sndFile.m_szNames[smp].empty()) ? std::string(m_sndFile.m_szNames[smp]) : "untitled");
  1309. sampleFilename = mpt::ToCString(m_sndFile.GetCharsetInternal(), (!sample.filename.empty()) ? sample.GetFilename() : m_sndFile.m_szNames[smp]);
  1310. SanitizeFilename(sampleName);
  1311. SanitizeFilename(sampleFilename);
  1312. mpt::ustring fileNameU = fileName.ToUnicode();
  1313. fileNameU = mpt::String::Replace(fileNameU, U_("%sample_number%"), mpt::ufmt::fmt(smp, numberFmt));
  1314. fileNameU = mpt::String::Replace(fileNameU, U_("%sample_filename%"), mpt::ToUnicode(sampleFilename));
  1315. fileNameU = mpt::String::Replace(fileNameU, U_("%sample_name%"), mpt::ToUnicode(sampleName));
  1316. fileName = mpt::PathString::FromUnicode(fileNameU);
  1317. // Need to enforce S3I for Adlib samples
  1318. if(isAdlib && saveFormat != dfS3I)
  1319. fileName = fileName.ReplaceExt(P_(".s3i"));
  1320. }
  1321. try
  1322. {
  1323. mpt::SafeOutputFile sf(fileName, std::ios::binary, mpt::FlushModeFromBool(TrackerSettings::Instance().MiscFlushFileBuffersOnSave));
  1324. mpt::ofstream &f = sf;
  1325. if(!f)
  1326. {
  1327. ok = false;
  1328. continue;
  1329. }
  1330. f.exceptions(f.exceptions() | std::ios::badbit | std::ios::failbit);
  1331. // Need to enforce S3I for Adlib samples
  1332. const auto thisFormat = isAdlib ? dfS3I : saveFormat;
  1333. if(thisFormat == dfRAW)
  1334. ok = m_sndFile.SaveRAWSample(smp, f);
  1335. else if(thisFormat == dfFLAC)
  1336. ok = m_sndFile.SaveFLACSample(smp, f);
  1337. else if(thisFormat == dfS3I)
  1338. ok = m_sndFile.SaveS3ISample(smp, f);
  1339. else
  1340. ok = m_sndFile.SaveWAVSample(smp, f);
  1341. } catch(const std::exception &)
  1342. {
  1343. ok = false;
  1344. }
  1345. if(ok)
  1346. {
  1347. m_sndFile.SetSamplePath(smp, fileName);
  1348. sample.uFlags.reset(SMP_MODIFIED);
  1349. UpdateView(SampleHint().Info());
  1350. // Check if any other samples refer to the same file - that would be dangerous.
  1351. if(sample.uFlags[SMP_KEEPONDISK])
  1352. {
  1353. for(SAMPLEINDEX i = 1; i <= m_sndFile.GetNumSamples(); i++)
  1354. {
  1355. if(i != smp && m_sndFile.GetSample(i).uFlags[SMP_KEEPONDISK] && m_sndFile.GetSamplePath(i) == m_sndFile.GetSamplePath(smp))
  1356. {
  1357. m_sndFile.GetSample(i).uFlags.reset(SMP_KEEPONDISK);
  1358. m_modDoc.UpdateAllViews(nullptr, SampleHint(i).Names().Info(), this);
  1359. }
  1360. }
  1361. }
  1362. }
  1363. }
  1364. }
  1365. EndWaitCursor();
  1366. if (!ok)
  1367. {
  1368. ErrorBox(IDS_ERR_SAVESMP, this);
  1369. } else
  1370. {
  1371. TrackerSettings::Instance().PathSamples.SetWorkingDir(dlg.GetWorkingDirectory());
  1372. }
  1373. SwitchToView();
  1374. }
  1375. void CCtrlSamples::OnSamplePlay()
  1376. {
  1377. if (m_modDoc.IsNotePlaying(NOTE_NONE, m_nSample, 0))
  1378. {
  1379. m_modDoc.NoteOff(0, true);
  1380. } else
  1381. {
  1382. m_modDoc.PlayNote(PlayNoteParam(NOTE_MIDDLEC).Sample(m_nSample));
  1383. }
  1384. SwitchToView();
  1385. }
  1386. template<typename T>
  1387. static bool DoNormalize(T *p, SmpLength selStart, SmpLength selEnd)
  1388. {
  1389. auto [min, max] = CViewSample::FindMinMax(p + selStart, selEnd - selStart, 1);
  1390. max = std::max(-min, max);
  1391. if(max < std::numeric_limits<T>::max())
  1392. {
  1393. max++;
  1394. for(SmpLength i = selStart; i < selEnd; i++)
  1395. {
  1396. p[i] = static_cast<T>((static_cast<int>(p[i]) << (sizeof(T) * 8 - 1)) / max);
  1397. }
  1398. return true;
  1399. }
  1400. return false;
  1401. }
  1402. void CCtrlSamples::Normalize(bool allSamples)
  1403. {
  1404. //Default case: Normalize current sample
  1405. SAMPLEINDEX minSample = m_nSample, maxSample = m_nSample;
  1406. //If only one sample is selected, parts of it may be amplified
  1407. SmpLength selStart = 0, selEnd = 0;
  1408. if(allSamples)
  1409. {
  1410. if(Reporting::Confirm(_T("This will normalize all samples independently. Continue?"), _T("Normalize")) == cnfNo)
  1411. return;
  1412. minSample = 1;
  1413. maxSample = m_sndFile.GetNumSamples();
  1414. } else
  1415. {
  1416. SampleSelectionPoints selection = GetSelectionPoints();
  1417. selStart = selection.nStart;
  1418. selEnd = selection.nEnd;
  1419. }
  1420. BeginWaitCursor();
  1421. bool modified = false;
  1422. for(SAMPLEINDEX smp = minSample; smp <= maxSample; smp++)
  1423. {
  1424. if(m_sndFile.GetSample(smp).HasSampleData())
  1425. {
  1426. ModSample &sample = m_sndFile.GetSample(smp);
  1427. if(minSample != maxSample)
  1428. {
  1429. // If more than one sample is selected, always amplify the whole sample.
  1430. selStart = 0;
  1431. selEnd = sample.nLength;
  1432. } else
  1433. {
  1434. // One sample: correct the boundaries, if needed
  1435. LimitMax(selEnd, sample.nLength);
  1436. LimitMax(selStart, selEnd);
  1437. if(selStart == selEnd)
  1438. {
  1439. selStart = 0;
  1440. selEnd = sample.nLength;
  1441. }
  1442. }
  1443. m_modDoc.GetSampleUndo().PrepareUndo(smp, sundo_update, "Normalize", selStart, selEnd);
  1444. selStart *= sample.GetNumChannels();
  1445. selEnd *= sample.GetNumChannels();
  1446. if(sample.uFlags[CHN_16BIT])
  1447. {
  1448. modified |= DoNormalize(sample.sample16(), selStart, selEnd);
  1449. } else
  1450. {
  1451. modified |= DoNormalize(sample.sample8(), selStart, selEnd);
  1452. }
  1453. if(modified)
  1454. {
  1455. sample.PrecomputeLoops(m_sndFile, false);
  1456. m_modDoc.UpdateAllViews(nullptr, SampleHint(smp).Data());
  1457. }
  1458. }
  1459. }
  1460. if(modified)
  1461. {
  1462. SetModified(SampleHint().Data(), false, true);
  1463. }
  1464. EndWaitCursor();
  1465. SwitchToView();
  1466. }
  1467. void CCtrlSamples::OnNormalize()
  1468. {
  1469. Normalize(CMainFrame::GetInputHandler()->ShiftPressed());
  1470. }
  1471. void CCtrlSamples::RemoveDCOffset(bool allSamples)
  1472. {
  1473. SAMPLEINDEX minSample = m_nSample, maxSample = m_nSample;
  1474. //Shift -> Process all samples
  1475. if(allSamples)
  1476. {
  1477. if(Reporting::Confirm(_T("This will process all samples independently. Continue?"), _T("DC Offset Removal")) == cnfNo)
  1478. return;
  1479. minSample = 1;
  1480. maxSample = m_sndFile.GetNumSamples();
  1481. }
  1482. BeginWaitCursor();
  1483. // for report / SetModified
  1484. SAMPLEINDEX numModified = 0;
  1485. double reportOffset = 0;
  1486. for(SAMPLEINDEX smp = minSample; smp <= maxSample; smp++)
  1487. {
  1488. SmpLength selStart, selEnd;
  1489. if(!m_sndFile.GetSample(smp).HasSampleData())
  1490. continue;
  1491. if (minSample != maxSample)
  1492. {
  1493. selStart = 0;
  1494. selEnd = m_sndFile.GetSample(smp).nLength;
  1495. } else
  1496. {
  1497. SampleSelectionPoints selection = GetSelectionPoints();
  1498. selStart = selection.nStart;
  1499. selEnd = selection.nEnd;
  1500. }
  1501. m_modDoc.GetSampleUndo().PrepareUndo(smp, sundo_update, "Remove DC Offset", selStart, selEnd);
  1502. const double offset = SampleEdit::RemoveDCOffset(m_sndFile.GetSample(smp), selStart, selEnd, m_sndFile);
  1503. if(offset == 0.0f) // No offset removed.
  1504. continue;
  1505. reportOffset += offset;
  1506. numModified++;
  1507. m_modDoc.UpdateAllViews(nullptr, SampleHint(smp).Info().Data());
  1508. }
  1509. EndWaitCursor();
  1510. SwitchToView();
  1511. // fill the statusbar with some nice information
  1512. CString dcInfo;
  1513. if(numModified)
  1514. {
  1515. SetModified(SampleHint().Info().Data(), true, true);
  1516. if(numModified == 1)
  1517. {
  1518. dcInfo.Format(_T("Removed DC offset (%.1f%%)"), reportOffset * 100);
  1519. } else
  1520. {
  1521. dcInfo.Format(_T("Removed DC offset from %u samples (avg %0.1f%%)"), numModified, reportOffset / numModified * 100);
  1522. }
  1523. } else
  1524. {
  1525. dcInfo.SetString(_T("No DC offset found"));
  1526. }
  1527. CMainFrame *pMainFrm = CMainFrame::GetMainFrame();
  1528. pMainFrm->SetXInfoText(dcInfo);
  1529. }
  1530. void CCtrlSamples::OnRemoveDCOffset()
  1531. {
  1532. RemoveDCOffset(CMainFrame::GetInputHandler()->ShiftPressed());
  1533. }
  1534. void CCtrlSamples::ApplyAmplify(const double amp, const double fadeInStart, const double fadeOutEnd, const bool fadeIn, const bool fadeOut, const Fade::Law fadeLaw)
  1535. {
  1536. ModSample &sample = m_sndFile.GetSample(m_nSample);
  1537. if(!sample.HasSampleData() || sample.uFlags[CHN_ADLIB]) return;
  1538. BeginWaitCursor();
  1539. SampleSelectionPoints selection = GetSelectionPoints();
  1540. const auto start = selection.nStart, end = selection.nEnd, mid = (start + end) / 2;
  1541. PrepareUndo("Amplify", sundo_update, start, end);
  1542. if(fadeIn && fadeOut)
  1543. {
  1544. SampleEdit::AmplifySample(sample, start, mid, fadeInStart, amp, true, fadeLaw, m_sndFile);
  1545. SampleEdit::AmplifySample(sample, mid, end, amp, fadeOutEnd, false, fadeLaw, m_sndFile);
  1546. } else if(fadeIn)
  1547. {
  1548. SampleEdit::AmplifySample(sample, start, end, fadeInStart, amp, true, fadeLaw, m_sndFile);
  1549. } else if(fadeOut)
  1550. {
  1551. SampleEdit::AmplifySample(sample, start, end, amp, fadeOutEnd, false, fadeLaw, m_sndFile);
  1552. } else
  1553. {
  1554. SampleEdit::AmplifySample(sample, start, end, amp, amp, true, Fade::kLinear, m_sndFile);
  1555. }
  1556. sample.PrecomputeLoops(m_sndFile, false);
  1557. SetModified(SampleHint().Data(), false, true);
  1558. EndWaitCursor();
  1559. SwitchToView();
  1560. }
  1561. void CCtrlSamples::OnAmplify()
  1562. {
  1563. static CAmpDlg::AmpSettings settings { Fade::kLinear, 0, 0, 100, false, false };
  1564. CAmpDlg dlg(this, settings);
  1565. if (dlg.DoModal() != IDOK) return;
  1566. ApplyAmplify(settings.factor / 100.0, settings.fadeInStart / 100.0, settings.fadeOutEnd / 100.0, settings.fadeIn, settings.fadeOut, settings.fadeLaw);
  1567. }
  1568. // Quickly fade the selection in/out without asking the user.
  1569. // Fade-In is applied if the selection starts at the beginning of the sample.
  1570. // Fade-Out is applied if the selection ends and the end of the sample.
  1571. void CCtrlSamples::OnQuickFade()
  1572. {
  1573. ModSample &sample = m_sndFile.GetSample(m_nSample);
  1574. if(!sample.HasSampleData() || sample.uFlags[CHN_ADLIB]) return;
  1575. SampleSelectionPoints sel = GetSelectionPoints();
  1576. if(sel.selectionActive && (sel.nStart == 0 || sel.nEnd == sample.nLength))
  1577. {
  1578. ApplyAmplify(1.0, (sel.nStart == 0) ? 0.0 : 1.0, (sel.nEnd == sample.nLength) ? 0.0 : 1.0, sel.nStart == 0, sel.nEnd == sample.nLength, Fade::kLinear);
  1579. } else
  1580. {
  1581. // Can't apply quick fade as no appropriate selection has been made, so ask the user to amplify the whole sample instead.
  1582. OnAmplify();
  1583. }
  1584. }
  1585. void CCtrlSamples::OnResample()
  1586. {
  1587. ModSample &sample = m_sndFile.GetSample(m_nSample);
  1588. if(!sample.HasSampleData() || sample.uFlags[CHN_ADLIB])
  1589. return;
  1590. SAMPLEINDEX first = m_nSample, last = m_nSample;
  1591. if(CMainFrame::GetInputHandler()->ShiftPressed())
  1592. {
  1593. first = 1;
  1594. last = m_sndFile.GetNumSamples();
  1595. }
  1596. const uint32 oldRate = sample.GetSampleRate(m_sndFile.GetType());
  1597. CResamplingDlg dlg(this, oldRate, TrackerSettings::Instance().sampleEditorDefaultResampler, first != last);
  1598. if(dlg.DoModal() != IDOK)
  1599. return;
  1600. TrackerSettings::Instance().sampleEditorDefaultResampler = dlg.GetFilter();
  1601. for(SAMPLEINDEX smp = first; smp <= last; smp++)
  1602. {
  1603. const uint32 sampleFreq = m_sndFile.GetSample(smp).GetSampleRate(m_sndFile.GetType());
  1604. uint32 newFreq = dlg.GetFrequency();
  1605. if(dlg.GetResamplingOption() == CResamplingDlg::Upsample)
  1606. newFreq = sampleFreq * 2;
  1607. else if(dlg.GetResamplingOption() == CResamplingDlg::Downsample)
  1608. newFreq = sampleFreq / 2;
  1609. else if(newFreq == sampleFreq)
  1610. continue;
  1611. ApplyResample(smp, newFreq, dlg.GetFilter(), first != last, dlg.UpdatePatternCommands());
  1612. }
  1613. }
  1614. void CCtrlSamples::ApplyResample(SAMPLEINDEX smp, uint32 newRate, ResamplingMode mode, bool ignoreSelection, bool updatePatternCommands)
  1615. {
  1616. BeginWaitCursor();
  1617. ModSample &sample = m_sndFile.GetSample(smp);
  1618. if(!sample.HasSampleData() || sample.uFlags[CHN_ADLIB])
  1619. {
  1620. EndWaitCursor();
  1621. return;
  1622. }
  1623. SampleSelectionPoints selection = GetSelectionPoints();
  1624. LimitMax(selection.nEnd, sample.nLength);
  1625. if(selection.nStart >= selection.nEnd || ignoreSelection)
  1626. {
  1627. selection.nStart = 0;
  1628. selection.nEnd = sample.nLength;
  1629. }
  1630. const uint32 oldRate = sample.GetSampleRate(m_sndFile.GetType());
  1631. if(newRate < 1 || oldRate < 1)
  1632. {
  1633. MessageBeep(MB_ICONWARNING);
  1634. EndWaitCursor();
  1635. return;
  1636. }
  1637. const SmpLength oldLength = sample.nLength;
  1638. const SmpLength selLength = (selection.nEnd - selection.nStart);
  1639. const SmpLength newSelLength = Util::muldivr_unsigned(selLength, newRate, oldRate);
  1640. const SmpLength newSelEnd = selection.nStart + newSelLength;
  1641. const SmpLength newTotalLength = sample.nLength - selLength + newSelLength;
  1642. const uint8 numChannels = sample.GetNumChannels();
  1643. if(newTotalLength <= 1)
  1644. {
  1645. MessageBeep(MB_ICONWARNING);
  1646. EndWaitCursor();
  1647. return;
  1648. }
  1649. void *newSample = ModSample::AllocateSample(newTotalLength, sample.GetBytesPerSample());
  1650. if(newSample != nullptr)
  1651. {
  1652. // First, copy parts of the sample that are not affected by partial upsampling
  1653. const SmpLength bps = sample.GetBytesPerSample();
  1654. std::memcpy(newSample, sample.sampleb(), selection.nStart * bps);
  1655. std::memcpy(static_cast<char *>(newSample) + newSelEnd * bps, sample.sampleb() + selection.nEnd * bps, (sample.nLength - selection.nEnd) * bps);
  1656. if(mode == SRCMODE_DEFAULT)
  1657. {
  1658. // Resample using r8brain
  1659. const SmpLength bufferSize = std::min(std::max(selLength, SmpLength(oldRate)), SmpLength(1024 * 1024));
  1660. std::vector<double> convBuffer(bufferSize);
  1661. r8b::CDSPResampler16 resampler(oldRate, newRate, bufferSize);
  1662. for(uint8 chn = 0; chn < numChannels; chn++)
  1663. {
  1664. if(chn != 0) resampler.clear();
  1665. SmpLength readCount = selLength, writeCount = newSelLength;
  1666. SmpLength readOffset = selection.nStart * numChannels + chn, writeOffset = readOffset;
  1667. SmpLength outLatency = newRate;
  1668. double *outBuffer, lastVal = 0.0;
  1669. {
  1670. // Pre-fill the resampler with the first sampling point.
  1671. // Otherwise, it will assume that all samples before the first sampling point are 0,
  1672. // which can lead to unwanted artefacts (ripples) if the sample doesn't start with a zero crossing.
  1673. double firstVal = 0.0;
  1674. switch(sample.GetElementarySampleSize())
  1675. {
  1676. case 1:
  1677. firstVal = SC::Convert<double, int8>()(sample.sample8()[readOffset]);
  1678. lastVal = SC::Convert<double, int8>()(sample.sample8()[readOffset + selLength - numChannels]);
  1679. break;
  1680. case 2:
  1681. firstVal = SC::Convert<double, int16>()(sample.sample16()[readOffset]);
  1682. lastVal = SC::Convert<double, int16>()(sample.sample16()[readOffset + selLength - numChannels]);
  1683. break;
  1684. default:
  1685. // When higher bit depth is added, feel free to also replace CDSPResampler16 by CDSPResampler24 above.
  1686. MPT_ASSERT_MSG(false, "Bit depth not implemented");
  1687. }
  1688. // 10ms or less would probably be enough, but we will pre-fill the buffer with exactly "oldRate" samples
  1689. // to prevent any further rounding errors when using smaller buffers or when dividing oldRate or newRate.
  1690. uint32 remain = oldRate;
  1691. for(SmpLength i = 0; i < bufferSize; i++) convBuffer[i] = firstVal;
  1692. while(remain > 0)
  1693. {
  1694. uint32 procIn = std::min(remain, mpt::saturate_cast<uint32>(bufferSize));
  1695. SmpLength procCount = resampler.process(convBuffer.data(), procIn, outBuffer);
  1696. MPT_ASSERT(procCount <= outLatency);
  1697. LimitMax(procCount, outLatency);
  1698. outLatency -= procCount;
  1699. remain -= procIn;
  1700. }
  1701. }
  1702. // Now we can start with the actual resampling work...
  1703. while(writeCount > 0)
  1704. {
  1705. SmpLength smpCount = (SmpLength)convBuffer.size();
  1706. if(readCount != 0)
  1707. {
  1708. LimitMax(smpCount, readCount);
  1709. switch(sample.GetElementarySampleSize())
  1710. {
  1711. case 1:
  1712. CopySample<SC::ConversionChain<SC::Convert<double, int8>, SC::DecodeIdentity<int8> > >(convBuffer.data(), smpCount, 1, sample.sample8() + readOffset, sample.GetSampleSizeInBytes(), sample.GetNumChannels());
  1713. break;
  1714. case 2:
  1715. CopySample<SC::ConversionChain<SC::Convert<double, int16>, SC::DecodeIdentity<int16> > >(convBuffer.data(), smpCount, 1, sample.sample16() + readOffset, sample.GetSampleSizeInBytes(), sample.GetNumChannels());
  1716. break;
  1717. }
  1718. readOffset += smpCount * numChannels;
  1719. readCount -= smpCount;
  1720. } else
  1721. {
  1722. // Nothing to read, but still to write (compensate for r8brain's output latency)
  1723. for(SmpLength i = 0; i < smpCount; i++) convBuffer[i] = lastVal;
  1724. }
  1725. SmpLength procCount = resampler.process(convBuffer.data(), smpCount, outBuffer);
  1726. const SmpLength procLatency = std::min(outLatency, procCount);
  1727. procCount = std::min(procCount- procLatency, writeCount);
  1728. switch(sample.GetElementarySampleSize())
  1729. {
  1730. case 1:
  1731. CopySample<SC::ConversionChain<SC::Convert<int8, double>, SC::DecodeIdentity<double> > >(static_cast<int8 *>(newSample) + writeOffset, procCount, sample.GetNumChannels(), outBuffer + procLatency, procCount * sizeof(double), 1);
  1732. break;
  1733. case 2:
  1734. CopySample<SC::ConversionChain<SC::Convert<int16, double>, SC::DecodeIdentity<double> > >(static_cast<int16 *>(newSample) + writeOffset, procCount, sample.GetNumChannels(), outBuffer + procLatency, procCount * sizeof(double), 1);
  1735. break;
  1736. }
  1737. writeOffset += procCount * numChannels;
  1738. writeCount -= procCount;
  1739. outLatency -= procLatency;
  1740. }
  1741. }
  1742. } else
  1743. {
  1744. // Resample using built-in filters
  1745. uint32 functionNdx = MixFuncTable::ResamplingModeToMixFlags(mode);
  1746. if(sample.uFlags[CHN_16BIT]) functionNdx |= MixFuncTable::ndx16Bit;
  1747. if(sample.uFlags[CHN_STEREO]) functionNdx |= MixFuncTable::ndxStereo;
  1748. ModChannel chn{};
  1749. chn.pCurrentSample = sample.samplev();
  1750. chn.increment = SamplePosition::Ratio(oldRate, newRate);
  1751. chn.position.Set(selection.nStart);
  1752. chn.leftVol = chn.rightVol = (1 << 8);
  1753. chn.nLength = sample.nLength;
  1754. SmpLength writeCount = newSelLength;
  1755. SmpLength writeOffset = selection.nStart * sample.GetNumChannels();
  1756. while(writeCount > 0)
  1757. {
  1758. SmpLength procCount = std::min(static_cast<SmpLength>(MIXBUFFERSIZE), writeCount);
  1759. mixsample_t buffer[MIXBUFFERSIZE * 2];
  1760. MemsetZero(buffer);
  1761. MixFuncTable::Functions[functionNdx](chn, m_sndFile.m_Resampler, buffer, procCount);
  1762. for(uint8 c = 0; c < numChannels; c++)
  1763. {
  1764. switch(sample.GetElementarySampleSize())
  1765. {
  1766. case 1:
  1767. CopySample<SC::ConversionChain<SC::ConvertFixedPoint<int8, mixsample_t, 23>, SC::DecodeIdentity<mixsample_t> > >(static_cast<int8 *>(newSample) + writeOffset + c, procCount, sample.GetNumChannels(), buffer + c, sizeof(buffer), 2);
  1768. break;
  1769. case 2:
  1770. CopySample<SC::ConversionChain<SC::ConvertFixedPoint<int16, mixsample_t, 23>, SC::DecodeIdentity<mixsample_t> > >(static_cast<int16 *>(newSample) + writeOffset + c, procCount, sample.GetNumChannels(), buffer + c, sizeof(buffer), 2);
  1771. break;
  1772. }
  1773. }
  1774. writeCount -= procCount;
  1775. writeOffset += procCount * sample.GetNumChannels();
  1776. }
  1777. }
  1778. m_modDoc.GetSampleUndo().PrepareUndo(smp, sundo_replace, (newRate > oldRate) ? "Upsample" : "Downsample");
  1779. // Adjust loops and cues
  1780. const auto oldCues = sample.cues;
  1781. for(SmpLength &point : SampleEdit::GetCuesAndLoops(sample))
  1782. {
  1783. if(point >= oldLength)
  1784. point = newTotalLength;
  1785. else if(point >= selection.nEnd)
  1786. point += newSelLength - selLength;
  1787. else if(point > selection.nStart)
  1788. point = selection.nStart + Util::muldivr_unsigned(point - selection.nStart, newRate, oldRate);
  1789. LimitMax(point, newTotalLength);
  1790. }
  1791. if(updatePatternCommands)
  1792. {
  1793. bool patternUndoCreated = false;
  1794. m_sndFile.Patterns.ForEachModCommand([&](ModCommand &m)
  1795. {
  1796. if(m.command != CMD_OFFSET && m.command != CMD_REVERSEOFFSET && m.command != CMD_OFFSETPERCENTAGE)
  1797. return;
  1798. if(m_sndFile.GetSampleIndex(m.note, m.instr) != smp)
  1799. return;
  1800. SmpLength point = m.param * 256u;
  1801. if(m.command == CMD_OFFSETPERCENTAGE || (m.volcmd == VOLCMD_OFFSET && m.vol == 0))
  1802. point = Util::muldivr_unsigned(point, oldLength, 65536);
  1803. else if(m.volcmd == VOLCMD_OFFSET && m.vol <= std::size(oldCues))
  1804. point += oldCues[m.vol - 1];
  1805. if(point >= oldLength)
  1806. point = newTotalLength;
  1807. else if (point >= selection.nEnd)
  1808. point += newSelLength - selLength;
  1809. else if (point > selection.nStart)
  1810. point = selection.nStart + Util::muldivr_unsigned(point - selection.nStart, newRate, oldRate);
  1811. LimitMax(point, newTotalLength);
  1812. if(m.command == CMD_OFFSETPERCENTAGE || (m.volcmd == VOLCMD_OFFSET && m.vol == 0))
  1813. point = Util::muldivr_unsigned(point, 65536, newTotalLength);
  1814. else if(m.volcmd == VOLCMD_OFFSET && m.vol <= std::size(sample.cues))
  1815. point -= sample.cues[m.vol - 1];
  1816. if(!patternUndoCreated)
  1817. {
  1818. patternUndoCreated = true;
  1819. m_modDoc.PrepareUndoForAllPatterns(false, "Resample (Adjust Offsets)");
  1820. }
  1821. m.param = mpt::saturate_cast<ModCommand::PARAM>(point / 256u);
  1822. });
  1823. }
  1824. if(!selection.selectionActive)
  1825. {
  1826. if(m_sndFile.GetType() != MOD_TYPE_MOD)
  1827. {
  1828. sample.nC5Speed = newRate;
  1829. sample.FrequencyToTranspose();
  1830. }
  1831. }
  1832. ctrlSmp::ReplaceSample(sample, newSample, newTotalLength, m_sndFile);
  1833. // Update loop wrap-around buffer
  1834. sample.PrecomputeLoops(m_sndFile);
  1835. auto updateHint = SampleHint(smp).Info().Data();
  1836. if(sample.uFlags[SMP_KEEPONDISK] && !sample.uFlags[SMP_MODIFIED])
  1837. updateHint.Names();
  1838. sample.uFlags.set(SMP_MODIFIED);
  1839. m_modDoc.SetModified();
  1840. m_modDoc.UpdateAllViews(nullptr, updateHint, nullptr);
  1841. if(selection.selectionActive && !ignoreSelection)
  1842. {
  1843. SetSelectionPoints(selection.nStart, newSelEnd);
  1844. }
  1845. }
  1846. EndWaitCursor();
  1847. SwitchToView();
  1848. }
  1849. void CCtrlSamples::ReadTimeStretchParameters()
  1850. {
  1851. m_nSequenceMs = GetDlgItemInt(IDC_EDIT10);
  1852. m_nSeekWindowMs = GetDlgItemInt(IDC_EDIT11);
  1853. m_nOverlapMs = GetDlgItemInt(IDC_EDIT12);
  1854. }
  1855. void CCtrlSamples::UpdateTimeStretchParameters()
  1856. {
  1857. GetDlgItem(IDC_EDIT10)->SetWindowText(((m_nSequenceMs <= 0) ? _T("auto") : MPT_TFORMAT("{}ms")(m_nSequenceMs)).c_str());
  1858. GetDlgItem(IDC_EDIT11)->SetWindowText(((m_nSeekWindowMs <= 0) ? _T("auto") : MPT_TFORMAT("{}ms")(m_nSeekWindowMs)).c_str());
  1859. GetDlgItem(IDC_EDIT12)->SetWindowText(((m_nOverlapMs <= 0) ? _T("auto") : MPT_TFORMAT("{}ms")(m_nOverlapMs)).c_str());
  1860. }
  1861. void CCtrlSamples::OnEnableStretchToSize()
  1862. {
  1863. // Enable time-stretching / disable unused pitch-shifting UI elements
  1864. bool timeStretch = IsDlgButtonChecked(IDC_CHECK3) != BST_UNCHECKED;
  1865. if(!timeStretch) ReadTimeStretchParameters();
  1866. ((CComboBox *)GetDlgItem(IDC_COMBO4))->EnableWindow(timeStretch ? FALSE : TRUE);
  1867. ((CEdit *)GetDlgItem(IDC_EDIT6))->EnableWindow(timeStretch ? TRUE : FALSE);
  1868. ((CButton *)GetDlgItem(IDC_BUTTON2))->EnableWindow(timeStretch ? TRUE : FALSE);
  1869. GetDlgItem(IDC_TEXT_PITCH)->SetWindowText(timeStretch ? _T("Sequence") : _T("Pitch"));
  1870. GetDlgItem(IDC_TEXT_QUALITY)->SetWindowText(timeStretch ? _T("Seek Window") : _T("Quality"));
  1871. GetDlgItem(IDC_TEXT_FFT)->SetWindowText(timeStretch ? _T("Overlap") : _T("FFT Size"));
  1872. GetDlgItem(IDC_EDIT10)->ShowWindow(timeStretch ? SW_SHOW : SW_HIDE);
  1873. GetDlgItem(IDC_EDIT11)->ShowWindow(timeStretch ? SW_SHOW : SW_HIDE);
  1874. GetDlgItem(IDC_EDIT12)->ShowWindow(timeStretch ? SW_SHOW : SW_HIDE);
  1875. GetDlgItem(IDC_SPIN10)->ShowWindow(timeStretch ? SW_SHOW : SW_HIDE);
  1876. GetDlgItem(IDC_SPIN14)->ShowWindow(timeStretch ? SW_SHOW : SW_HIDE);
  1877. GetDlgItem(IDC_SPIN15)->ShowWindow(timeStretch ? SW_SHOW : SW_HIDE);
  1878. GetDlgItem(IDC_COMBO4)->ShowWindow(timeStretch ? SW_HIDE : SW_SHOW);
  1879. GetDlgItem(IDC_COMBO5)->ShowWindow(timeStretch ? SW_HIDE : SW_SHOW);
  1880. GetDlgItem(IDC_COMBO6)->ShowWindow(timeStretch ? SW_HIDE : SW_SHOW);
  1881. SetDlgItemText(IDC_BUTTON1, timeStretch ? _T("Time Stretch") : _T("Pitch Shift"));
  1882. if(timeStretch)
  1883. UpdateTimeStretchParameters();
  1884. }
  1885. void CCtrlSamples::OnEstimateSampleSize()
  1886. {
  1887. if(!m_sndFile.GetSample(m_nSample).HasSampleData())
  1888. return;
  1889. //Ensure m_dTimeStretchRatio is up-to-date with textbox content
  1890. UpdateData(TRUE);
  1891. //Open dialog
  1892. CPSRatioCalc dlg(m_sndFile, m_nSample, m_dTimeStretchRatio, this);
  1893. if (dlg.DoModal() != IDOK) return;
  1894. //Update ratio value&textbox
  1895. m_dTimeStretchRatio = dlg.m_dRatio;
  1896. UpdateData(FALSE);
  1897. }
  1898. enum TimeStretchPitchShiftResult
  1899. {
  1900. kUnknown,
  1901. kOK,
  1902. kAbort,
  1903. kInvalidRatio,
  1904. kStretchTooShort,
  1905. kStretchTooLong,
  1906. kOutOfMemory,
  1907. kSampleTooShort,
  1908. kStretchInvalidSampleRate,
  1909. };
  1910. class DoPitchShiftTimeStretch : public CProgressDialog
  1911. {
  1912. public:
  1913. CCtrlSamples &m_parent;
  1914. CModDoc &m_modDoc;
  1915. const float m_ratio;
  1916. TimeStretchPitchShiftResult m_result = kUnknown;
  1917. uint32 m_updateInterval;
  1918. const SAMPLEINDEX m_sample;
  1919. const bool m_pitchShift;
  1920. DoPitchShiftTimeStretch(CCtrlSamples &parent, CModDoc &modDoc, SAMPLEINDEX sample, float ratio, bool pitchShift)
  1921. : CProgressDialog(&parent)
  1922. , m_parent(parent)
  1923. , m_modDoc(modDoc)
  1924. , m_ratio(ratio)
  1925. , m_sample(sample)
  1926. , m_pitchShift(pitchShift)
  1927. {
  1928. m_updateInterval = TrackerSettings::Instance().GUIUpdateInterval;
  1929. if(m_updateInterval < 15) m_updateInterval = 15;
  1930. }
  1931. void Run() override
  1932. {
  1933. SetTitle(m_pitchShift ? _T("Pitch Shift") : _T("Time Stretch"));
  1934. SetRange(0, 100);
  1935. if(m_pitchShift)
  1936. m_result = PitchShift();
  1937. else
  1938. m_result = TimeStretch();
  1939. EndDialog((m_result == kOK) ? IDOK : IDCANCEL);
  1940. }
  1941. TimeStretchPitchShiftResult TimeStretch()
  1942. {
  1943. ModSample &sample = m_modDoc.GetSoundFile().GetSample(m_sample);
  1944. const uint32 sampleRate = sample.GetSampleRate(m_modDoc.GetModType());
  1945. if(!sample.HasSampleData()) return kAbort;
  1946. if(m_ratio == 1.0) return kAbort;
  1947. if(m_ratio < 0.5f) return kStretchTooShort;
  1948. if(m_ratio > 2.0f) return kStretchTooLong;
  1949. if(sampleRate > 192000) return kStretchInvalidSampleRate;
  1950. HANDLE handleSt = soundtouch_createInstance();
  1951. if(handleSt == NULL)
  1952. {
  1953. mpt::throw_out_of_memory();
  1954. }
  1955. const uint8 smpSize = sample.GetElementarySampleSize();
  1956. const uint8 numChannels = sample.GetNumChannels();
  1957. // Initialize soundtouch object.
  1958. soundtouch_setSampleRate(handleSt, sampleRate);
  1959. soundtouch_setChannels(handleSt, numChannels);
  1960. // Given ratio is time stretch ratio, and must be converted to
  1961. // tempo change ratio: for example time stretch ratio 2 means
  1962. // tempo change ratio 0.5.
  1963. soundtouch_setTempoChange(handleSt, (1.0f / m_ratio - 1.0f) * 100.0f);
  1964. // Read settings from GUI.
  1965. m_parent.ReadTimeStretchParameters();
  1966. // Set settings to soundtouch. Zero value means 'use default', and
  1967. // setting value is read back after setting because not all settings are accepted.
  1968. soundtouch_setSetting(handleSt, SETTING_SEQUENCE_MS, m_parent.m_nSequenceMs);
  1969. m_parent.m_nSequenceMs = soundtouch_getSetting(handleSt, SETTING_SEQUENCE_MS);
  1970. soundtouch_setSetting(handleSt, SETTING_SEEKWINDOW_MS, m_parent.m_nSeekWindowMs);
  1971. m_parent.m_nSeekWindowMs = soundtouch_getSetting(handleSt, SETTING_SEEKWINDOW_MS);
  1972. soundtouch_setSetting(handleSt, SETTING_OVERLAP_MS, m_parent.m_nOverlapMs);
  1973. m_parent.m_nOverlapMs = soundtouch_getSetting(handleSt, SETTING_OVERLAP_MS);
  1974. // Update GUI with the actual SoundTouch parameters in effect.
  1975. m_parent.UpdateTimeStretchParameters();
  1976. const SmpLength inBatchSize = soundtouch_getSetting(handleSt, SETTING_NOMINAL_INPUT_SEQUENCE) + 1; // approximate value, add 1 to play safe
  1977. const SmpLength outBatchSize = soundtouch_getSetting(handleSt, SETTING_NOMINAL_OUTPUT_SEQUENCE) + 1; // approximate value, add 1 to play safe
  1978. const auto selection = m_parent.GetSelectionPoints();
  1979. const SmpLength selLength = selection.selectionActive ? selection.nEnd - selection.nStart : sample.nLength;
  1980. const SmpLength remainLength = sample.nLength - selLength;
  1981. if(selLength < inBatchSize)
  1982. {
  1983. soundtouch_destroyInstance(handleSt);
  1984. return kSampleTooShort;
  1985. }
  1986. if(static_cast<SmpLength>(std::ceil(static_cast<double>(m_ratio) * selLength)) < outBatchSize)
  1987. {
  1988. soundtouch_destroyInstance(handleSt);
  1989. return kSampleTooShort;
  1990. }
  1991. const SmpLength stretchLength = mpt::saturate_round<SmpLength>(m_ratio * selLength);
  1992. const SmpLength stretchEnd = selection.nStart + stretchLength;
  1993. const SmpLength newSampleLength = remainLength + stretchLength;
  1994. void *pNewSample = nullptr;
  1995. if(newSampleLength <= MAX_SAMPLE_LENGTH)
  1996. {
  1997. pNewSample = ModSample::AllocateSample(newSampleLength, sample.GetBytesPerSample());
  1998. }
  1999. if(pNewSample == nullptr)
  2000. {
  2001. soundtouch_destroyInstance(handleSt);
  2002. return kOutOfMemory;
  2003. }
  2004. // Show wait mouse cursor
  2005. BeginWaitCursor();
  2006. memcpy(pNewSample, sample.sampleb(), selection.nStart * sample.GetBytesPerSample());
  2007. memcpy(static_cast<std::byte *>(pNewSample) + stretchEnd * sample.GetBytesPerSample(), sample.sampleb() + selection.nEnd * sample.GetBytesPerSample(), (sample.nLength - selection.nEnd) * sample.GetBytesPerSample());
  2008. constexpr SmpLength MaxInputChunkSize = 1024;
  2009. std::vector<float> buffer(MaxInputChunkSize * numChannels);
  2010. SmpLength inPos = selection.nStart;
  2011. SmpLength outPos = selection.nStart; // Keeps count of the sample length received from stretching process.
  2012. DWORD timeLast = 0;
  2013. // Process sample in steps.
  2014. while(inPos < selection.nEnd)
  2015. {
  2016. // Current chunk size limit test
  2017. const SmpLength inChunkSize = std::min(MaxInputChunkSize, sample.nLength - inPos);
  2018. DWORD timeNow = timeGetTime();
  2019. if(timeNow - timeLast >= m_updateInterval)
  2020. {
  2021. // Show progress bar using process button painting & text label
  2022. TCHAR progress[32];
  2023. uint32 percent = static_cast<uint32>(100 * (inPos + inChunkSize) / sample.nLength);
  2024. wsprintf(progress, _T("Time Stretch... %u%%"), percent);
  2025. SetText(progress);
  2026. SetProgress(percent);
  2027. ProcessMessages();
  2028. if(m_abort)
  2029. break;
  2030. timeLast = timeNow;
  2031. }
  2032. // Send sampledata for processing.
  2033. switch(smpSize)
  2034. {
  2035. case 1:
  2036. CopyAudioChannelsInterleaved(buffer.data(), sample.sample8() + inPos * numChannels, numChannels, inChunkSize);
  2037. break;
  2038. case 2:
  2039. CopyAudioChannelsInterleaved(buffer.data(), sample.sample16() + inPos * numChannels, numChannels, inChunkSize);
  2040. break;
  2041. }
  2042. soundtouch_putSamples(handleSt, buffer.data(), inChunkSize);
  2043. // Receive some processed samples (it's not guaranteed that there is any available).
  2044. {
  2045. SmpLength outChunkSize = std::min(static_cast<SmpLength>(soundtouch_numSamples(handleSt)), stretchLength - outPos);
  2046. if(outChunkSize > 0)
  2047. {
  2048. buffer.resize(outChunkSize * numChannels);
  2049. soundtouch_receiveSamples(handleSt, buffer.data(), outChunkSize);
  2050. switch(smpSize)
  2051. {
  2052. case 1:
  2053. CopyAudioChannelsInterleaved(static_cast<int8 *>(pNewSample) + numChannels * outPos, buffer.data(), numChannels, outChunkSize);
  2054. break;
  2055. case 2:
  2056. CopyAudioChannelsInterleaved(static_cast<int16 *>(pNewSample) + numChannels * outPos, buffer.data(), numChannels, outChunkSize);
  2057. break;
  2058. }
  2059. outPos += outChunkSize;
  2060. }
  2061. }
  2062. // Next buffer chunk
  2063. inPos += inChunkSize;
  2064. }
  2065. if(!m_abort)
  2066. {
  2067. // The input sample should now be processed. Receive remaining samples.
  2068. soundtouch_flush(handleSt);
  2069. SmpLength outChunkSize = std::min(static_cast<SmpLength>(soundtouch_numSamples(handleSt)), stretchLength - (outPos - selection.nStart));
  2070. if(outChunkSize > 0)
  2071. {
  2072. buffer.resize(outChunkSize * numChannels);
  2073. soundtouch_receiveSamples(handleSt, buffer.data(), outChunkSize);
  2074. switch(smpSize)
  2075. {
  2076. case 1:
  2077. CopyAudioChannelsInterleaved(static_cast<int8 *>(pNewSample) + numChannels * outPos, buffer.data(), numChannels, outChunkSize);
  2078. break;
  2079. case 2:
  2080. CopyAudioChannelsInterleaved(static_cast<int16 *>(pNewSample) + numChannels * outPos, buffer.data(), numChannels, outChunkSize);
  2081. break;
  2082. }
  2083. outPos += outChunkSize;
  2084. }
  2085. soundtouch_clear(handleSt);
  2086. MPT_ASSERT(soundtouch_isEmpty(handleSt) != 0);
  2087. CSoundFile &sndFile = m_modDoc.GetSoundFile();
  2088. m_parent.PrepareUndo("Time Stretch", sundo_replace);
  2089. // Swap sample buffer pointer to new buffer, update song + sample data & free old sample buffer
  2090. ctrlSmp::ReplaceSample(sample, pNewSample, std::min(outPos + remainLength, newSampleLength), sndFile);
  2091. // Update loops and wrap-around buffer
  2092. sample.SetLoop(
  2093. mpt::saturate_round<SmpLength>(sample.nLoopStart * m_ratio),
  2094. mpt::saturate_round<SmpLength>(sample.nLoopEnd * m_ratio),
  2095. sample.uFlags[CHN_LOOP],
  2096. sample.uFlags[CHN_PINGPONGLOOP],
  2097. sndFile);
  2098. sample.SetSustainLoop(
  2099. mpt::saturate_round<SmpLength>(sample.nSustainStart * m_ratio),
  2100. mpt::saturate_round<SmpLength>(sample.nSustainEnd * m_ratio),
  2101. sample.uFlags[CHN_SUSTAINLOOP],
  2102. sample.uFlags[CHN_PINGPONGSUSTAIN],
  2103. sndFile);
  2104. } else
  2105. {
  2106. ModSample::FreeSample(pNewSample);
  2107. }
  2108. soundtouch_destroyInstance(handleSt);
  2109. // Restore mouse cursor
  2110. EndWaitCursor();
  2111. if(selection.selectionActive)
  2112. m_parent.SetSelectionPoints(selection.nStart, selection.nStart + stretchLength);
  2113. return m_abort ? kAbort : kOK;
  2114. }
  2115. TimeStretchPitchShiftResult PitchShift()
  2116. {
  2117. static constexpr SmpLength MAX_BUFFER_LENGTH = 8192;
  2118. ModSample &sample = m_modDoc.GetSoundFile().GetSample(m_sample);
  2119. if(!sample.HasSampleData() || m_ratio < 0.5f || m_ratio > 2.0f)
  2120. {
  2121. return kAbort;
  2122. }
  2123. // Get selected oversampling - quality - (also refered as FFT overlapping) factor
  2124. CComboBox *combo = (CComboBox *)m_parent.GetDlgItem(IDC_COMBO5);
  2125. long ovs = combo->GetCurSel() + 4;
  2126. // Get selected FFT size (power of 2; should not exceed MAX_BUFFER_LENGTH - see smbPitchShift.h)
  2127. combo = (CComboBox *)m_parent.GetDlgItem(IDC_COMBO6);
  2128. UINT fft = 1 << (combo->GetCurSel() + 8);
  2129. while(fft > MAX_BUFFER_LENGTH) fft >>= 1;
  2130. // Show wait mouse cursor
  2131. BeginWaitCursor();
  2132. // Get original sample rate
  2133. const float sampleRate = static_cast<float>(sample.GetSampleRate(m_modDoc.GetModType()));
  2134. // Allocate working buffer
  2135. const size_t bufferSize = MAX_BUFFER_LENGTH + fft;
  2136. std::vector<float> buffer;
  2137. try
  2138. {
  2139. buffer.resize(bufferSize);
  2140. } catch(mpt::out_of_memory e)
  2141. {
  2142. mpt::delete_out_of_memory(e);
  2143. return kOutOfMemory;
  2144. }
  2145. const auto smpSize = sample.GetElementarySampleSize();
  2146. const auto numChans = sample.GetNumChannels();
  2147. const auto bps = sample.GetBytesPerSample();
  2148. int8 *pNewSample = static_cast<int8 *>(ModSample::AllocateSample(sample.nLength, bps));
  2149. if(pNewSample == nullptr)
  2150. return kOutOfMemory;
  2151. DWORD timeLast = 0;
  2152. const auto selection = m_parent.GetSelectionPoints();
  2153. // Process each channel separately
  2154. for(uint8 chn = 0; chn < numChans; chn++)
  2155. {
  2156. // Process sample buffer using MAX_BUFFER_LENGTH (max) sized chunk steps (in order to allow
  2157. // the processing of BIG samples...)
  2158. for(SmpLength pos = selection.nStart; pos < selection.nEnd;)
  2159. {
  2160. DWORD timeNow = timeGetTime();
  2161. if(timeNow - timeLast >= m_updateInterval)
  2162. {
  2163. TCHAR progress[32];
  2164. uint32 percent = static_cast<uint32>(chn * 50.0 + (100.0 / numChans) * (pos - selection.nStart) / (selection.nEnd - selection.nStart));
  2165. wsprintf(progress, _T("Pitch Shift... %u%%"), percent);
  2166. SetText(progress);
  2167. SetProgress(percent);
  2168. ProcessMessages();
  2169. if(m_abort)
  2170. break;
  2171. timeLast = timeNow;
  2172. }
  2173. // TRICK : output buffer offset management
  2174. // as the pitch-shifter adds some blank signal in head of output buffer (matching FFT
  2175. // length - in short it needs a certain amount of data before being able to output some
  2176. // meaningful processed samples) , in order to avoid this behaviour , we will ignore
  2177. // the first FFT_length samples and process the same amount of extra blank samples
  2178. // (all 0.0f) at the end of the buffer (those extra samples will benefit from internal
  2179. // FFT data computed during the previous steps resulting in a correct and consistent
  2180. // signal output).
  2181. const SmpLength processLen = (pos + MAX_BUFFER_LENGTH <= selection.nEnd) ? MAX_BUFFER_LENGTH : (selection.nEnd - pos);
  2182. const bool bufStart = (pos == selection.nStart);
  2183. const bool bufEnd = (pos + processLen >= selection.nEnd);
  2184. const SmpLength startOffset = (bufStart ? fft : 0);
  2185. const SmpLength innerOffset = (bufStart ? 0 : fft);
  2186. const SmpLength finalOffset = (bufEnd ? fft : 0);
  2187. // Re-initialize pitch-shifter with blank FFT before processing 1st chunk of current channel
  2188. if(bufStart)
  2189. {
  2190. std::fill(buffer.begin(), buffer.begin() + fft, 0.0f);
  2191. smbPitchShift(m_ratio, fft, fft, ovs, sampleRate, buffer.data(), buffer.data());
  2192. }
  2193. // Convert current channel's data chunk to float
  2194. SmpLength offset = pos * numChans + chn;
  2195. switch(smpSize)
  2196. {
  2197. case 1:
  2198. CopySample<SC::ConversionChain<SC::Convert<float, int8>, SC::DecodeIdentity<int8>>>(buffer.data(), processLen, 1, sample.sample8() + offset, sizeof(int8) * processLen * numChans, numChans);
  2199. break;
  2200. case 2:
  2201. CopySample<SC::ConversionChain<SC::Convert<float, int16>, SC::DecodeIdentity<int16>>>(buffer.data(), processLen, 1, sample.sample16() + offset, sizeof(int16) * processLen * numChans, numChans);
  2202. break;
  2203. }
  2204. // Fills extra blank samples (read TRICK description comment above)
  2205. if(bufEnd)
  2206. std::fill(buffer.begin() + processLen, buffer.begin() + processLen + finalOffset, 0.0f);
  2207. // Apply pitch shifting
  2208. smbPitchShift(m_ratio, static_cast<long>(processLen + finalOffset), fft, ovs, sampleRate, buffer.data(), buffer.data());
  2209. // Restore pitched-shifted float sample into original sample buffer
  2210. void *ptr = pNewSample + (pos - innerOffset) * smpSize * numChans + chn * smpSize;
  2211. const SmpLength copyLength = processLen + finalOffset - startOffset + 1;
  2212. switch(smpSize)
  2213. {
  2214. case 1:
  2215. CopySample<SC::ConversionChain<SC::Convert<int8, float>, SC::DecodeIdentity<float>>>(static_cast<int8 *>(ptr), copyLength, numChans, buffer.data() + startOffset, sizeof(float) * bufferSize, 1);
  2216. break;
  2217. case 2:
  2218. CopySample<SC::ConversionChain<SC::Convert<int16, float>, SC::DecodeIdentity<float>>>(static_cast<int16 *>(ptr), copyLength, numChans, buffer.data() + startOffset, sizeof(float) * bufferSize, 1);
  2219. break;
  2220. }
  2221. // Next buffer chunk
  2222. pos += processLen;
  2223. }
  2224. }
  2225. if(!m_abort)
  2226. {
  2227. m_parent.PrepareUndo("Pitch Shift", sundo_replace);
  2228. memcpy(pNewSample, sample.sampleb(), selection.nStart * bps);
  2229. memcpy(pNewSample + selection.nEnd * bps, sample.sampleb() + selection.nEnd * bps, (sample.nLength - selection.nEnd) * bps);
  2230. ctrlSmp::ReplaceSample(sample, pNewSample, sample.nLength, m_modDoc.GetSoundFile());
  2231. } else
  2232. {
  2233. ModSample::FreeSample(pNewSample);
  2234. }
  2235. // Restore mouse cursor
  2236. EndWaitCursor();
  2237. return m_abort ? kAbort : kOK;
  2238. }
  2239. };
  2240. void CCtrlSamples::OnPitchShiftTimeStretch()
  2241. {
  2242. TimeStretchPitchShiftResult errorcode = kAbort;
  2243. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2244. if(!sample.HasSampleData()) goto error;
  2245. if(IsDlgButtonChecked(IDC_CHECK3))
  2246. {
  2247. // Time stretching
  2248. UpdateData(TRUE); //Ensure m_dTimeStretchRatio is up-to-date with textbox content
  2249. DoPitchShiftTimeStretch timeStretch(*this, m_modDoc, m_nSample, static_cast<float>(m_dTimeStretchRatio / 100.0), false);
  2250. timeStretch.DoModal();
  2251. errorcode = timeStretch.m_result;
  2252. } else
  2253. {
  2254. // Pitch shifting
  2255. // Get selected pitch modifier [-12,+12]
  2256. CString text;
  2257. static_cast<CComboBox *>(GetDlgItem(IDC_COMBO4))->GetWindowText(text);
  2258. float pm = ConvertStrTo<float>(text);
  2259. if(pm == 0.0f) goto error;
  2260. // Compute pitch ratio in range [0.5f ; 2.0f] (1.0f means output == input)
  2261. // * pitch up -> 1.0f + n / 12.0f -> (12.0f + n) / 12.0f , considering n : pitch modifier > 0
  2262. // * pitch dn -> 1.0f - n / 24.0f -> (24.0f - n) / 24.0f , considering n : pitch modifier > 0
  2263. float pitch = pm < 0 ? ((24.0f + pm) / 24.0f) : ((12.0f + pm) / 12.0f);
  2264. // Apply pitch modifier
  2265. DoPitchShiftTimeStretch pitchShift(*this, m_modDoc, m_nSample, pitch, true);
  2266. pitchShift.DoModal();
  2267. errorcode = pitchShift.m_result;
  2268. }
  2269. if(errorcode == kOK)
  2270. {
  2271. // Update sample view
  2272. SetModified(SampleHint().Info().Data(), true, true);
  2273. return;
  2274. }
  2275. // Error management
  2276. error:
  2277. if(errorcode != kAbort)
  2278. {
  2279. CString str;
  2280. switch(errorcode)
  2281. {
  2282. case kInvalidRatio:
  2283. str = _T("Invalid stretch ratio!");
  2284. break;
  2285. case kStretchTooShort:
  2286. case kStretchTooLong:
  2287. str = MPT_CFORMAT("Stretch ratio is too {}. Must be between 50% and 200%.")((errorcode == kStretchTooShort) ? CString(_T("low")) : CString(_T("high")));
  2288. break;
  2289. case kOutOfMemory:
  2290. str = _T("Out of memory.");
  2291. break;
  2292. case kSampleTooShort:
  2293. str = _T("Sample too short.");
  2294. break;
  2295. case kStretchInvalidSampleRate:
  2296. str = _T("Sample rate must be 192,000 Hz or lower.");
  2297. break;
  2298. default:
  2299. str = _T("Unknown Error.");
  2300. break;
  2301. }
  2302. Reporting::Error(str);
  2303. }
  2304. }
  2305. void CCtrlSamples::OnReverse()
  2306. {
  2307. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2308. SampleSelectionPoints selection = GetSelectionPoints();
  2309. PrepareUndo("Reverse", sundo_reverse, selection.nStart, selection.nEnd);
  2310. if(SampleEdit::ReverseSample(sample, selection.nStart, selection.nEnd, m_sndFile))
  2311. {
  2312. SetModified(SampleHint().Data(), false, true);
  2313. } else
  2314. {
  2315. m_modDoc.GetSampleUndo().RemoveLastUndoStep(m_nSample);
  2316. }
  2317. EndWaitCursor();
  2318. SwitchToView();
  2319. }
  2320. void CCtrlSamples::OnInvert()
  2321. {
  2322. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2323. SampleSelectionPoints selection = GetSelectionPoints();
  2324. PrepareUndo("Invert", sundo_invert, selection.nStart, selection.nEnd);
  2325. if(SampleEdit::InvertSample(sample, selection.nStart, selection.nEnd, m_sndFile) == true)
  2326. {
  2327. SetModified(SampleHint().Data(), false, true);
  2328. } else
  2329. {
  2330. m_modDoc.GetSampleUndo().RemoveLastUndoStep(m_nSample);
  2331. }
  2332. EndWaitCursor();
  2333. SwitchToView();
  2334. }
  2335. void CCtrlSamples::OnSignUnSign()
  2336. {
  2337. if(!m_sndFile.GetSample(m_nSample).HasSampleData()) return;
  2338. if(m_modDoc.IsNotePlaying(0, m_nSample, 0))
  2339. MsgBoxHidable(ConfirmSignUnsignWhenPlaying);
  2340. BeginWaitCursor();
  2341. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2342. SampleSelectionPoints selection = GetSelectionPoints();
  2343. PrepareUndo("Unsign", sundo_unsign, selection.nStart, selection.nEnd);
  2344. if(SampleEdit::UnsignSample(sample, selection.nStart, selection.nEnd, m_sndFile) == true)
  2345. {
  2346. SetModified(SampleHint().Data(), false, true);
  2347. } else
  2348. {
  2349. m_modDoc.GetSampleUndo().RemoveLastUndoStep(m_nSample);
  2350. }
  2351. EndWaitCursor();
  2352. SwitchToView();
  2353. }
  2354. void CCtrlSamples::OnSilence()
  2355. {
  2356. if(!m_sndFile.GetSample(m_nSample).HasSampleData()) return;
  2357. BeginWaitCursor();
  2358. SampleSelectionPoints selection = GetSelectionPoints();
  2359. // never apply silence to a sample that has no selection
  2360. const SmpLength len = selection.nEnd - selection.nStart;
  2361. if(selection.selectionActive && len > 1)
  2362. {
  2363. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2364. PrepareUndo("Silence", sundo_update, selection.nStart, selection.nEnd);
  2365. if(SampleEdit::SilenceSample(sample, selection.nStart, selection.nEnd, m_sndFile))
  2366. {
  2367. SetModified(SampleHint().Data(), false, true);
  2368. }
  2369. }
  2370. EndWaitCursor();
  2371. SwitchToView();
  2372. }
  2373. void CCtrlSamples::OnPrevInstrument()
  2374. {
  2375. if (m_nSample > 1)
  2376. SetCurrentSample(m_nSample - 1);
  2377. else
  2378. SetCurrentSample(m_sndFile.GetNumSamples());
  2379. }
  2380. void CCtrlSamples::OnNextInstrument()
  2381. {
  2382. if (m_nSample < m_sndFile.GetNumSamples())
  2383. SetCurrentSample(m_nSample + 1);
  2384. else
  2385. SetCurrentSample(1);
  2386. }
  2387. void CCtrlSamples::OnNameChanged()
  2388. {
  2389. if(IsLocked() || !m_nSample) return;
  2390. CString tmp;
  2391. m_EditName.GetWindowText(tmp);
  2392. const std::string s = mpt::ToCharset(m_sndFile.GetCharsetInternal(), tmp);
  2393. if(s != m_sndFile.m_szNames[m_nSample])
  2394. {
  2395. if(!m_startedEdit)
  2396. {
  2397. PrepareUndo("Set Name");
  2398. m_editInstrumentName = GetParentInstrumentWithSameName();
  2399. if(m_editInstrumentName != INSTRUMENTINDEX_INVALID)
  2400. m_modDoc.GetInstrumentUndo().PrepareUndo(m_editInstrumentName, "Set Name");
  2401. }
  2402. if(m_editInstrumentName <= m_sndFile.GetNumInstruments())
  2403. {
  2404. if(auto instr = m_sndFile.Instruments[m_editInstrumentName]; instr != nullptr)
  2405. {
  2406. instr->name = s;
  2407. m_modDoc.UpdateAllViews(nullptr, InstrumentHint(m_editInstrumentName).Names(), this);
  2408. }
  2409. }
  2410. m_sndFile.m_szNames[m_nSample] = s;
  2411. SetModified(SampleHint().Names(), false, false);
  2412. }
  2413. }
  2414. void CCtrlSamples::OnFileNameChanged()
  2415. {
  2416. if(IsLocked()) return;
  2417. CString tmp;
  2418. m_EditFileName.GetWindowText(tmp);
  2419. const std::string s = mpt::ToCharset(m_sndFile.GetCharsetInternal(), tmp);
  2420. if(s != m_sndFile.GetSample(m_nSample).filename)
  2421. {
  2422. if(!m_startedEdit) PrepareUndo("Set Filename");
  2423. m_sndFile.GetSample(m_nSample).filename = s;
  2424. SetModified(SampleHint().Info(), false, false);
  2425. }
  2426. }
  2427. void CCtrlSamples::OnVolumeChanged()
  2428. {
  2429. if (IsLocked()) return;
  2430. int nVol = GetDlgItemInt(IDC_EDIT7);
  2431. Limit(nVol, 0, 64);
  2432. nVol *= 4;
  2433. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2434. if (nVol != sample.nVolume)
  2435. {
  2436. if(!m_startedEdit) PrepareUndo("Set Default Volume");
  2437. sample.nVolume = static_cast<uint16>(nVol);
  2438. sample.uFlags.reset(SMP_NODEFAULTVOLUME);
  2439. SetModified(SampleHint().Info(), false, false);
  2440. }
  2441. }
  2442. void CCtrlSamples::OnGlobalVolChanged()
  2443. {
  2444. if (IsLocked()) return;
  2445. int nVol = GetDlgItemInt(IDC_EDIT8);
  2446. Limit(nVol, 0, 64);
  2447. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2448. if (nVol != sample.nGlobalVol)
  2449. {
  2450. if(!m_startedEdit) PrepareUndo("Set Global Volume");
  2451. sample.nGlobalVol = static_cast<uint16>(nVol);
  2452. // Live-adjust volume
  2453. for(auto &chn : m_sndFile.m_PlayState.Chn)
  2454. {
  2455. if(chn.pModSample == &sample)
  2456. {
  2457. chn.UpdateInstrumentVolume(chn.pModSample, chn.pModInstrument);
  2458. }
  2459. }
  2460. SetModified(SampleHint().Info(), false, false);
  2461. }
  2462. }
  2463. void CCtrlSamples::OnSetPanningChanged()
  2464. {
  2465. if (IsLocked()) return;
  2466. bool b = false;
  2467. if (m_sndFile.GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT))
  2468. {
  2469. b = IsDlgButtonChecked(IDC_CHECK1) != FALSE;
  2470. }
  2471. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2472. if(b != sample.uFlags[CHN_PANNING])
  2473. {
  2474. PrepareUndo("Toggle Panning");
  2475. sample.uFlags.set(CHN_PANNING, b);
  2476. SetModified(SampleHint().Info(), false, false);
  2477. }
  2478. }
  2479. void CCtrlSamples::OnPanningChanged()
  2480. {
  2481. if (IsLocked()) return;
  2482. int nPan = GetDlgItemInt(IDC_EDIT9);
  2483. if (nPan < 0) nPan = 0;
  2484. if (m_sndFile.GetType() == MOD_TYPE_XM)
  2485. {
  2486. if (nPan > 255) nPan = 255; // displayed panning will be 0-255 with XM
  2487. } else
  2488. {
  2489. if (nPan > 64) nPan = 64; // displayed panning will be 0-64 with anything but XM.
  2490. nPan = nPan * 4; // so we x4 to get MPT's internal 0-256 range.
  2491. }
  2492. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2493. if (nPan != sample.nPan)
  2494. {
  2495. if(!m_startedEdit) PrepareUndo("Set Panning");
  2496. sample.nPan = static_cast<uint16>(nPan);
  2497. SetModified(SampleHint().Info(), false, false);
  2498. }
  2499. }
  2500. void CCtrlSamples::OnFineTuneChanged()
  2501. {
  2502. if (IsLocked()) return;
  2503. int n = GetDlgItemInt(IDC_EDIT5);
  2504. if(!m_startedEdit)
  2505. PrepareUndo("Finetune");
  2506. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2507. if (!m_sndFile.UseFinetuneAndTranspose())
  2508. {
  2509. if ((n > 0) && (n <= (m_sndFile.GetType() == MOD_TYPE_S3M ? 65535 : 9999999)) && (n != (int)m_sndFile.GetSample(m_nSample).nC5Speed))
  2510. {
  2511. sample.nC5Speed = n;
  2512. int transp = ModSample::FrequencyToTranspose(n).first;
  2513. int basenote = (NOTE_MIDDLEC - NOTE_MIN) + transp;
  2514. Clamp(basenote, BASENOTE_MIN, BASENOTE_MAX);
  2515. basenote -= BASENOTE_MIN;
  2516. if (basenote != m_CbnBaseNote.GetCurSel())
  2517. {
  2518. LockControls();
  2519. m_CbnBaseNote.SetCurSel(basenote);
  2520. UnlockControls();
  2521. }
  2522. SetModified(SampleHint().Info(), false, false);
  2523. }
  2524. } else
  2525. {
  2526. if(m_sndFile.GetType() & MOD_TYPE_MOD)
  2527. n = MOD2XMFineTune(n);
  2528. if((n >= -128) && (n <= 127))
  2529. {
  2530. sample.nFineTune = static_cast<int8>(n);
  2531. SetModified(SampleHint().Info(), false, false);
  2532. }
  2533. }
  2534. }
  2535. void CCtrlSamples::OnFineTuneChangedDone()
  2536. {
  2537. // Update all playing channels
  2538. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2539. for(auto &chn : m_sndFile.m_PlayState.Chn)
  2540. {
  2541. if(chn.pModSample == &sample)
  2542. {
  2543. chn.nTranspose = sample.RelativeTone;
  2544. chn.nFineTune = sample.nFineTune;
  2545. if(chn.nC5Speed != 0 && sample.nC5Speed != 0)
  2546. {
  2547. if(m_sndFile.PeriodsAreFrequencies())
  2548. chn.nPeriod = Util::muldivr(chn.nPeriod, sample.nC5Speed, chn.nC5Speed);
  2549. else if(!m_sndFile.m_SongFlags[SONG_LINEARSLIDES])
  2550. chn.nPeriod = Util::muldivr(chn.nPeriod, chn.nC5Speed, sample.nC5Speed);
  2551. }
  2552. chn.nC5Speed = sample.nC5Speed;
  2553. }
  2554. }
  2555. }
  2556. void CCtrlSamples::OnBaseNoteChanged()
  2557. {
  2558. if (IsLocked()) return;
  2559. int n = static_cast<int>(m_CbnBaseNote.GetItemData(m_CbnBaseNote.GetCurSel()));
  2560. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2561. PrepareUndo("Transpose");
  2562. if(!m_sndFile.UseFinetuneAndTranspose())
  2563. {
  2564. const int oldTransp = ModSample::FrequencyToTranspose(sample.nC5Speed).first;
  2565. const uint32 newFreq = mpt::saturate_round<uint32>(sample.nC5Speed * std::pow(2.0, (n - oldTransp) / 12.0));
  2566. if (newFreq > 0 && newFreq <= (m_sndFile.GetType() == MOD_TYPE_S3M ? 65535u : 9999999u) && newFreq != sample.nC5Speed)
  2567. {
  2568. sample.nC5Speed = newFreq;
  2569. LockControls();
  2570. SetDlgItemInt(IDC_EDIT5, newFreq, FALSE);
  2571. // Due to rounding imprecisions if the base note is below 0, we recalculate it here to make sure that the value stays consistent.
  2572. int basenote = (NOTE_MIDDLEC - NOTE_MIN) + ModSample::FrequencyToTranspose(newFreq).first;
  2573. Limit(basenote, BASENOTE_MIN, BASENOTE_MAX);
  2574. basenote -= BASENOTE_MIN;
  2575. if(basenote != m_CbnBaseNote.GetCurSel())
  2576. m_CbnBaseNote.SetCurSel(basenote);
  2577. OnFineTuneChangedDone();
  2578. UnlockControls();
  2579. SetModified(SampleHint().Info(), false, false);
  2580. }
  2581. } else
  2582. {
  2583. if ((n >= -128) && (n < 128))
  2584. {
  2585. sample.RelativeTone = (int8)n;
  2586. OnFineTuneChangedDone();
  2587. SetModified(SampleHint().Info(), false, false);
  2588. }
  2589. }
  2590. }
  2591. void CCtrlSamples::OnVibTypeChanged()
  2592. {
  2593. if (IsLocked()) return;
  2594. int n = m_ComboAutoVib.GetCurSel();
  2595. if (n >= 0)
  2596. {
  2597. PrepareUndo("Set Vibrato Type");
  2598. m_sndFile.GetSample(m_nSample).nVibType = static_cast<VibratoType>(m_ComboAutoVib.GetItemData(n));
  2599. PropagateAutoVibratoChanges();
  2600. SetModified(SampleHint().Info(), false, false);
  2601. }
  2602. }
  2603. void CCtrlSamples::OnVibDepthChanged()
  2604. {
  2605. if (IsLocked()) return;
  2606. int lmin = 0, lmax = 0;
  2607. m_SpinVibDepth.GetRange(lmin, lmax);
  2608. int n = GetDlgItemInt(IDC_EDIT15);
  2609. if ((n >= lmin) && (n <= lmax))
  2610. {
  2611. if(!m_startedEdit) PrepareUndo("Set Vibrato Depth");
  2612. m_sndFile.GetSample(m_nSample).nVibDepth = static_cast<uint8>(n);
  2613. PropagateAutoVibratoChanges();
  2614. SetModified(SampleHint().Info(), false, false);
  2615. }
  2616. }
  2617. void CCtrlSamples::OnVibSweepChanged()
  2618. {
  2619. if (IsLocked()) return;
  2620. int lmin = 0, lmax = 0;
  2621. m_SpinVibSweep.GetRange(lmin, lmax);
  2622. int n = GetDlgItemInt(IDC_EDIT14);
  2623. if ((n >= lmin) && (n <= lmax))
  2624. {
  2625. if(!m_startedEdit) PrepareUndo("Set Vibrato Sweep");
  2626. m_sndFile.GetSample(m_nSample).nVibSweep = static_cast<uint8>(n);
  2627. PropagateAutoVibratoChanges();
  2628. SetModified(SampleHint().Info(), false, false);
  2629. }
  2630. }
  2631. void CCtrlSamples::OnVibRateChanged()
  2632. {
  2633. if (IsLocked()) return;
  2634. int lmin = 0, lmax = 0;
  2635. m_SpinVibRate.GetRange(lmin, lmax);
  2636. int n = GetDlgItemInt(IDC_EDIT16);
  2637. if ((n >= lmin) && (n <= lmax))
  2638. {
  2639. if(!m_startedEdit) PrepareUndo("Set Vibrato Rate");
  2640. m_sndFile.GetSample(m_nSample).nVibRate = static_cast<uint8>(n);
  2641. PropagateAutoVibratoChanges();
  2642. SetModified(SampleHint().Info(), false, false);
  2643. }
  2644. }
  2645. void CCtrlSamples::OnLoopTypeChanged()
  2646. {
  2647. if(IsLocked()) return;
  2648. const int n = m_ComboLoopType.GetCurSel();
  2649. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2650. bool wasDisabled = !sample.uFlags[CHN_LOOP];
  2651. PrepareUndo("Set Loop Type");
  2652. // Loop type index: 0: Off, 1: On, 2: PingPong
  2653. sample.uFlags.set(CHN_LOOP, n > 0);
  2654. sample.uFlags.set(CHN_PINGPONGLOOP, n == 2);
  2655. // set loop points if theren't any
  2656. if(wasDisabled && sample.uFlags[CHN_LOOP] && sample.nLoopStart == sample.nLoopEnd)
  2657. {
  2658. SampleSelectionPoints selection = GetSelectionPoints();
  2659. if(selection.selectionActive)
  2660. {
  2661. sample.SetLoop(selection.nStart, selection.nEnd, true, n == 2, m_sndFile);
  2662. } else
  2663. {
  2664. sample.SetLoop(0, sample.nLength, true, n == 2, m_sndFile);
  2665. }
  2666. m_modDoc.UpdateAllViews(NULL, SampleHint(m_nSample).Info());
  2667. } else
  2668. {
  2669. sample.PrecomputeLoops(m_sndFile);
  2670. }
  2671. ctrlSmp::UpdateLoopPoints(sample, m_sndFile);
  2672. SetModified(SampleHint().Info(), false, false);
  2673. }
  2674. void CCtrlSamples::OnLoopPointsChanged()
  2675. {
  2676. if(IsLocked()) return;
  2677. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2678. SmpLength start = GetDlgItemInt(IDC_EDIT1, NULL, FALSE), end = GetDlgItemInt(IDC_EDIT2, NULL, FALSE);
  2679. if(start < end || !sample.uFlags[CHN_LOOP])
  2680. {
  2681. if(!m_startedEdit) PrepareUndo("Set Loop");
  2682. const int n = m_ComboLoopType.GetCurSel();
  2683. sample.SetLoop(start, end, n > 0, n == 2, m_sndFile);
  2684. SetModified(SampleHint().Info(), false, false);
  2685. }
  2686. }
  2687. void CCtrlSamples::OnSustainTypeChanged()
  2688. {
  2689. if(IsLocked()) return;
  2690. const int n = m_ComboSustainType.GetCurSel();
  2691. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2692. bool wasDisabled = !sample.uFlags[CHN_SUSTAINLOOP];
  2693. PrepareUndo("Set Sustain Loop Type");
  2694. // Loop type index: 0: Off, 1: On, 2: PingPong
  2695. sample.uFlags.set(CHN_SUSTAINLOOP, n > 0);
  2696. sample.uFlags.set(CHN_PINGPONGSUSTAIN, n == 2);
  2697. // set sustain loop points if theren't any
  2698. if(wasDisabled && sample.uFlags[CHN_SUSTAINLOOP] && sample.nSustainStart == sample.nSustainEnd)
  2699. {
  2700. SampleSelectionPoints selection = GetSelectionPoints();
  2701. if(selection.selectionActive)
  2702. {
  2703. sample.SetSustainLoop(selection.nStart, selection.nEnd, true, n == 2, m_sndFile);
  2704. } else
  2705. {
  2706. sample.SetSustainLoop(0, sample.nLength, true, n == 2, m_sndFile);
  2707. }
  2708. m_modDoc.UpdateAllViews(NULL, SampleHint(m_nSample).Info());
  2709. } else
  2710. {
  2711. sample.PrecomputeLoops(m_sndFile);
  2712. }
  2713. ctrlSmp::UpdateLoopPoints(sample, m_sndFile);
  2714. SetModified(SampleHint().Info(), false, false);
  2715. }
  2716. void CCtrlSamples::OnSustainPointsChanged()
  2717. {
  2718. if(IsLocked()) return;
  2719. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2720. SmpLength start = GetDlgItemInt(IDC_EDIT3, NULL, FALSE), end = GetDlgItemInt(IDC_EDIT4, NULL, FALSE);
  2721. if(start < end || !sample.uFlags[CHN_SUSTAINLOOP])
  2722. {
  2723. if(!m_startedEdit) PrepareUndo("Set Sustain Loop");
  2724. const int n = m_ComboSustainType.GetCurSel();
  2725. sample.SetSustainLoop(start, end, n > 0, n == 2, m_sndFile);
  2726. SetModified(SampleHint().Info(), false, false);
  2727. }
  2728. }
  2729. #define SMPLOOP_ACCURACY 7 // 5%
  2730. #define BIDILOOP_ACCURACY 2 // 5%
  2731. bool MPT_LoopCheck(int sstart0, int sstart1, int send0, int send1)
  2732. {
  2733. int dse0 = send0 - sstart0;
  2734. if ((dse0 < -SMPLOOP_ACCURACY) || (dse0 > SMPLOOP_ACCURACY)) return false;
  2735. int dse1 = send1 - sstart1;
  2736. if ((dse1 < -SMPLOOP_ACCURACY) || (dse1 > SMPLOOP_ACCURACY)) return false;
  2737. int dstart = sstart1 - sstart0;
  2738. int dend = send1 - send0;
  2739. if (!dstart) dstart = dend >> 7;
  2740. if (!dend) dend = dstart >> 7;
  2741. if ((dstart ^ dend) < 0) return false;
  2742. int delta = dend - dstart;
  2743. return ((delta > -SMPLOOP_ACCURACY) && (delta < SMPLOOP_ACCURACY));
  2744. }
  2745. bool MPT_BidiEndCheck(int spos0, int spos1, int spos2)
  2746. {
  2747. int delta0 = spos1 - spos0;
  2748. int delta1 = spos2 - spos1;
  2749. int delta2 = spos2 - spos0;
  2750. if (!delta0) delta0 = delta1 >> 7;
  2751. if (!delta1) delta1 = delta0 >> 7;
  2752. if ((delta1 ^ delta0) < 0) return false;
  2753. return ((delta0 >= -1) && (delta0 <= 0) && (delta1 >= -1) && (delta1 <= 0) && (delta2 >= -1) && (delta2 <= 0));
  2754. }
  2755. bool MPT_BidiStartCheck(int spos0, int spos1, int spos2)
  2756. {
  2757. int delta1 = spos1 - spos0;
  2758. int delta0 = spos2 - spos1;
  2759. int delta2 = spos2 - spos0;
  2760. if (!delta0) delta0 = delta1 >> 7;
  2761. if (!delta1) delta1 = delta0 >> 7;
  2762. if ((delta1 ^ delta0) < 0) return false;
  2763. return ((delta0 >= -1) && (delta0 <= 0) && (delta1 > -1) && (delta1 <= 0) && (delta2 >= -1) && (delta2 <= 0));
  2764. }
  2765. void CCtrlSamples::OnVScroll(UINT nCode, UINT, CScrollBar *scrollBar)
  2766. {
  2767. TCHAR s[256];
  2768. if(IsLocked()) return;
  2769. ModSample &sample = m_sndFile.GetSample(m_nSample);
  2770. const uint8 *pSample = mpt::byte_cast<const uint8 *>(sample.sampleb());
  2771. const uint32 inc = sample.GetBytesPerSample();
  2772. SmpLength i;
  2773. int pos;
  2774. bool redraw = false;
  2775. static CScrollBar *lastScrollbar = nullptr;
  2776. LockControls();
  2777. if ((!sample.nLength) || (!pSample)) goto NoSample;
  2778. if (sample.uFlags[CHN_16BIT])
  2779. {
  2780. pSample++;
  2781. }
  2782. // Loop Start
  2783. if ((pos = m_SpinLoopStart.GetPos32()) != 0 && sample.nLoopEnd > 0)
  2784. {
  2785. bool bOk = false;
  2786. const uint8 *p = pSample + sample.nLoopStart * inc;
  2787. int find0 = (int)pSample[sample.nLoopEnd*inc-inc];
  2788. int find1 = (int)pSample[sample.nLoopEnd*inc];
  2789. // Find Next LoopStart Point
  2790. if (pos > 0)
  2791. {
  2792. for (i = sample.nLoopStart + 1; i + 16 < sample.nLoopEnd; i++)
  2793. {
  2794. p += inc;
  2795. bOk = sample.uFlags[CHN_PINGPONGLOOP] ? MPT_BidiStartCheck(p[0], p[inc], p[inc*2]) : MPT_LoopCheck(find0, find1, p[0], p[inc]);
  2796. if (bOk) break;
  2797. }
  2798. } else
  2799. // Find Prev LoopStart Point
  2800. {
  2801. for (i = sample.nLoopStart; i; )
  2802. {
  2803. i--;
  2804. p -= inc;
  2805. bOk = sample.uFlags[CHN_PINGPONGLOOP] ? MPT_BidiStartCheck(p[0], p[inc], p[inc*2]) : MPT_LoopCheck(find0, find1, p[0], p[inc]);
  2806. if (bOk) break;
  2807. }
  2808. }
  2809. if (bOk)
  2810. {
  2811. if(!m_startedEdit && lastScrollbar != scrollBar) PrepareUndo("Set Loop Start");
  2812. sample.nLoopStart = i;
  2813. wsprintf(s, _T("%u"), sample.nLoopStart);
  2814. m_EditLoopStart.SetWindowText(s);
  2815. redraw = true;
  2816. sample.PrecomputeLoops(m_sndFile);
  2817. }
  2818. m_SpinLoopStart.SetPos(0);
  2819. }
  2820. // Loop End
  2821. if ((pos = m_SpinLoopEnd.GetPos32()) != 0)
  2822. {
  2823. bool bOk = false;
  2824. const uint8 *p = pSample + sample.nLoopEnd * inc;
  2825. int find0 = (int)pSample[sample.nLoopStart*inc];
  2826. int find1 = (int)pSample[sample.nLoopStart*inc+inc];
  2827. // Find Next LoopEnd Point
  2828. if (pos > 0)
  2829. {
  2830. for (i = sample.nLoopEnd + 1; i <= sample.nLength; i++, p += inc)
  2831. {
  2832. bOk = sample.uFlags[CHN_PINGPONGLOOP] ? MPT_BidiEndCheck(p[0], p[inc], p[inc*2]) : MPT_LoopCheck(find0, find1, p[0], p[inc]);
  2833. if (bOk) break;
  2834. }
  2835. } else
  2836. // Find Prev LoopEnd Point
  2837. {
  2838. for (i = sample.nLoopEnd; i > sample.nLoopStart + 16; )
  2839. {
  2840. i--;
  2841. p -= inc;
  2842. bOk = sample.uFlags[CHN_PINGPONGLOOP] ? MPT_BidiEndCheck(p[0], p[inc], p[inc*2]) : MPT_LoopCheck(find0, find1, p[0], p[inc]);
  2843. if (bOk) break;
  2844. }
  2845. }
  2846. if (bOk)
  2847. {
  2848. if(!m_startedEdit && lastScrollbar != scrollBar) PrepareUndo("Set Loop End");
  2849. sample.nLoopEnd = i;
  2850. wsprintf(s, _T("%u"), sample.nLoopEnd);
  2851. m_EditLoopEnd.SetWindowText(s);
  2852. redraw = true;
  2853. sample.PrecomputeLoops(m_sndFile);
  2854. }
  2855. m_SpinLoopEnd.SetPos(0);
  2856. }
  2857. // Sustain Loop Start
  2858. if ((pos = m_SpinSustainStart.GetPos32()) != 0 && sample.nSustainEnd > 0)
  2859. {
  2860. bool bOk = false;
  2861. const uint8 *p = pSample + sample.nSustainStart * inc;
  2862. int find0 = (int)pSample[sample.nSustainEnd*inc-inc];
  2863. int find1 = (int)pSample[sample.nSustainEnd*inc];
  2864. // Find Next Sustain LoopStart Point
  2865. if (pos > 0)
  2866. {
  2867. for (i = sample.nSustainStart + 1; i + 16 < sample.nSustainEnd; i++)
  2868. {
  2869. p += inc;
  2870. bOk = sample.uFlags[CHN_PINGPONGSUSTAIN] ? MPT_BidiStartCheck(p[0], p[inc], p[inc*2]) : MPT_LoopCheck(find0, find1, p[0], p[inc]);
  2871. if (bOk) break;
  2872. }
  2873. } else
  2874. // Find Prev Sustain LoopStart Point
  2875. {
  2876. for (i = sample.nSustainStart; i; )
  2877. {
  2878. i--;
  2879. p -= inc;
  2880. bOk = sample.uFlags[CHN_PINGPONGSUSTAIN] ? MPT_BidiStartCheck(p[0], p[inc], p[inc*2]) : MPT_LoopCheck(find0, find1, p[0], p[inc]);
  2881. if (bOk) break;
  2882. }
  2883. }
  2884. if (bOk)
  2885. {
  2886. if(!m_startedEdit && lastScrollbar != scrollBar) PrepareUndo("Set Sustain Loop Start");
  2887. sample.nSustainStart = i;
  2888. wsprintf(s, _T("%u"), sample.nSustainStart);
  2889. m_EditSustainStart.SetWindowText(s);
  2890. redraw = true;
  2891. sample.PrecomputeLoops(m_sndFile);
  2892. }
  2893. m_SpinSustainStart.SetPos(0);
  2894. }
  2895. // Sustain Loop End
  2896. if ((pos = m_SpinSustainEnd.GetPos32()) != 0)
  2897. {
  2898. bool bOk = false;
  2899. const uint8 *p = pSample + sample.nSustainEnd * inc;
  2900. int find0 = (int)pSample[sample.nSustainStart*inc];
  2901. int find1 = (int)pSample[sample.nSustainStart*inc+inc];
  2902. // Find Next LoopEnd Point
  2903. if (pos > 0)
  2904. {
  2905. for (i = sample.nSustainEnd + 1; i + 1 < sample.nLength; i++, p += inc)
  2906. {
  2907. bOk = sample.uFlags[CHN_PINGPONGSUSTAIN] ? MPT_BidiEndCheck(p[0], p[inc], p[inc*2]) : MPT_LoopCheck(find0, find1, p[0], p[inc]);
  2908. if (bOk) break;
  2909. }
  2910. } else
  2911. // Find Prev LoopEnd Point
  2912. {
  2913. for (i = sample.nSustainEnd; i > sample.nSustainStart + 16; )
  2914. {
  2915. i--;
  2916. p -= inc;
  2917. bOk = sample.uFlags[CHN_PINGPONGSUSTAIN] ? MPT_BidiEndCheck(p[0], p[inc], p[inc*2]) : MPT_LoopCheck(find0, find1, p[0], p[inc]);
  2918. if (bOk) break;
  2919. }
  2920. }
  2921. if (bOk)
  2922. {
  2923. if(!m_startedEdit && lastScrollbar != scrollBar) PrepareUndo("Set Sustain Loop End");
  2924. sample.nSustainEnd = i;
  2925. wsprintf(s, _T("%u"), sample.nSustainEnd);
  2926. m_EditSustainEnd.SetWindowText(s);
  2927. redraw = true;
  2928. sample.PrecomputeLoops(m_sndFile);
  2929. }
  2930. m_SpinSustainEnd.SetPos(0);
  2931. }
  2932. NoSample:
  2933. // FineTune / C-5 Speed
  2934. if ((pos = m_SpinFineTune.GetPos32()) != 0)
  2935. {
  2936. if (!m_sndFile.UseFinetuneAndTranspose())
  2937. {
  2938. if(!m_startedEdit && lastScrollbar != scrollBar) PrepareUndo("Finetune");
  2939. if(sample.nC5Speed < 1)
  2940. sample.nC5Speed = 8363;
  2941. auto oldFreq = sample.nC5Speed;
  2942. sample.Transpose((pos * TrackerSettings::Instance().m_nFinetuneStep) / 1200.0);
  2943. if(sample.nC5Speed == oldFreq)
  2944. sample.nC5Speed += pos;
  2945. Limit(sample.nC5Speed, 1u, 9999999u); // 9999999 is max. in Impulse Tracker
  2946. int transp = ModSample::FrequencyToTranspose(sample.nC5Speed).first;
  2947. int basenote = (NOTE_MIDDLEC - NOTE_MIN) + transp;
  2948. Clamp(basenote, BASENOTE_MIN, BASENOTE_MAX);
  2949. basenote -= BASENOTE_MIN;
  2950. if (basenote != m_CbnBaseNote.GetCurSel()) m_CbnBaseNote.SetCurSel(basenote);
  2951. SetDlgItemInt(IDC_EDIT5, sample.nC5Speed, FALSE);
  2952. } else
  2953. {
  2954. if(!m_startedEdit && lastScrollbar != scrollBar) PrepareUndo("Finetune");
  2955. int ftune = (int)sample.nFineTune;
  2956. // MOD finetune range -8 to 7 translates to -128 to 112
  2957. if(m_sndFile.GetType() & MOD_TYPE_MOD)
  2958. {
  2959. ftune = Clamp((ftune >> 4) + pos, -8, 7);
  2960. sample.nFineTune = MOD2XMFineTune((signed char)ftune);
  2961. } else
  2962. {
  2963. ftune = Clamp(ftune + pos, -128, 127);
  2964. sample.nFineTune = (signed char)ftune;
  2965. }
  2966. SetDlgItemInt(IDC_EDIT5, ftune, TRUE);
  2967. }
  2968. redraw = true;
  2969. m_SpinFineTune.SetPos(0);
  2970. OnFineTuneChangedDone();
  2971. }
  2972. if(scrollBar->m_hWnd == m_SpinSequenceMs.m_hWnd || scrollBar->m_hWnd == m_SpinSeekWindowMs.m_hWnd || scrollBar->m_hWnd == m_SpinOverlap.m_hWnd)
  2973. {
  2974. ReadTimeStretchParameters();
  2975. UpdateTimeStretchParameters();
  2976. }
  2977. if(nCode == SB_ENDSCROLL) SwitchToView();
  2978. if(redraw)
  2979. {
  2980. SetModified(SampleHint().Info().Data(), false, false);
  2981. }
  2982. lastScrollbar = scrollBar;
  2983. UnlockControls();
  2984. }
  2985. BOOL CCtrlSamples::PreTranslateMessage(MSG *pMsg)
  2986. {
  2987. if (pMsg)
  2988. {
  2989. //We handle keypresses before Windows has a chance to handle them (for alt etc..)
  2990. if ((pMsg->message == WM_SYSKEYUP) || (pMsg->message == WM_KEYUP) ||
  2991. (pMsg->message == WM_SYSKEYDOWN) || (pMsg->message == WM_KEYDOWN))
  2992. {
  2993. CInputHandler* ih = CMainFrame::GetInputHandler();
  2994. //Translate message manually
  2995. UINT nChar = (UINT)pMsg->wParam;
  2996. UINT nRepCnt = LOWORD(pMsg->lParam);
  2997. UINT nFlags = HIWORD(pMsg->lParam);
  2998. KeyEventType kT = ih->GetKeyEventType(nFlags);
  2999. InputTargetContext ctx = (InputTargetContext)(kCtxViewSamples);
  3000. if (ih->KeyEvent(ctx, nChar, nRepCnt, nFlags, kT) != kcNull)
  3001. return true; // Mapped to a command, no need to pass message on.
  3002. }
  3003. }
  3004. return CModControlDlg::PreTranslateMessage(pMsg);
  3005. }
  3006. LRESULT CCtrlSamples::OnCustomKeyMsg(WPARAM wParam, LPARAM /*lParam*/)
  3007. {
  3008. int transpose = 0;
  3009. switch(wParam)
  3010. {
  3011. case kcSampleLoad: OnSampleOpen(); return wParam;
  3012. case kcSampleLoadRaw: OnSampleOpenRaw(); return wParam;
  3013. case kcSampleSave: OnSampleSaveOne(); return wParam;
  3014. case kcSampleNew: InsertSample(false); return wParam;
  3015. case kcSampleDuplicate: InsertSample(true); return wParam;
  3016. case kcSampleTransposeUp: transpose = 1; break;
  3017. case kcSampleTransposeDown: transpose = -1; break;
  3018. case kcSampleTransposeOctUp: transpose = 12; break;
  3019. case kcSampleTransposeOctDown: transpose = -12; break;
  3020. case kcSampleUpsample:
  3021. case kcSampleDownsample:
  3022. {
  3023. uint32 oldRate = m_sndFile.GetSample(m_nSample).GetSampleRate(m_sndFile.GetType());
  3024. ApplyResample(m_nSample, wParam == kcSampleUpsample ? oldRate * 2 : oldRate / 2, TrackerSettings::Instance().sampleEditorDefaultResampler);
  3025. }
  3026. return wParam;
  3027. case kcSampleResample:
  3028. OnResample();
  3029. return wParam;
  3030. case kcSampleStereoSep:
  3031. OnStereoSeparation();
  3032. return wParam;
  3033. case kcSampleInitializeOPL:
  3034. OnInitOPLInstrument();
  3035. return wParam;
  3036. }
  3037. if(transpose)
  3038. {
  3039. if(m_CbnBaseNote.IsWindowEnabled())
  3040. {
  3041. int sel = Clamp(m_CbnBaseNote.GetCurSel() + transpose, 0, m_CbnBaseNote.GetCount() - 1);
  3042. if(sel != m_CbnBaseNote.GetCurSel())
  3043. {
  3044. m_CbnBaseNote.SetCurSel(sel);
  3045. OnBaseNoteChanged();
  3046. }
  3047. }
  3048. return wParam;
  3049. }
  3050. return kcNull;
  3051. }
  3052. // Return currently selected part of the sample.
  3053. // The whole sample size will be returned if no part of the sample is selected.
  3054. // However, point.bSelected indicates whether a sample selection exists or not.
  3055. CCtrlSamples::SampleSelectionPoints CCtrlSamples::GetSelectionPoints()
  3056. {
  3057. SampleSelectionPoints points;
  3058. SAMPLEVIEWSTATE viewstate;
  3059. const ModSample &sample = m_sndFile.GetSample(m_nSample);
  3060. Clear(viewstate);
  3061. SendViewMessage(VIEWMSG_SAVESTATE, (LPARAM)&viewstate);
  3062. points.nStart = viewstate.dwBeginSel;
  3063. points.nEnd = viewstate.dwEndSel;
  3064. if(points.nEnd > sample.nLength) points.nEnd = sample.nLength;
  3065. if(points.nStart > points.nEnd) points.nStart = points.nEnd;
  3066. points.selectionActive = true;
  3067. if(points.nStart >= points.nEnd)
  3068. {
  3069. points.nStart = 0;
  3070. points.nEnd = sample.nLength;
  3071. points.selectionActive = false;
  3072. }
  3073. return points;
  3074. }
  3075. // Set the currently selected part of the sample.
  3076. // To reset the selection, use nStart = nEnd = 0.
  3077. void CCtrlSamples::SetSelectionPoints(SmpLength nStart, SmpLength nEnd)
  3078. {
  3079. const ModSample &sample = m_sndFile.GetSample(m_nSample);
  3080. Limit(nStart, SmpLength(0), sample.nLength);
  3081. Limit(nEnd, SmpLength(0), sample.nLength);
  3082. SAMPLEVIEWSTATE viewstate;
  3083. Clear(viewstate);
  3084. SendViewMessage(VIEWMSG_SAVESTATE, (LPARAM)&viewstate);
  3085. viewstate.dwBeginSel = nStart;
  3086. viewstate.dwEndSel = nEnd;
  3087. SendViewMessage(VIEWMSG_LOADSTATE, (LPARAM)&viewstate);
  3088. }
  3089. // Crossfade loop to create smooth loop transitions
  3090. void CCtrlSamples::OnXFade()
  3091. {
  3092. ModSample &sample = m_sndFile.GetSample(m_nSample);
  3093. if(!sample.HasSampleData())
  3094. {
  3095. MessageBeep(MB_ICONWARNING);
  3096. SwitchToView();
  3097. return;
  3098. }
  3099. bool resetLoopOnCancel = false;
  3100. if((sample.nLoopEnd <= sample.nLoopStart || sample.nLoopEnd > sample.nLength)
  3101. && (sample.nSustainEnd <= sample.nSustainStart || sample.nSustainEnd > sample.nLength))
  3102. {
  3103. const auto selection = GetSelectionPoints();
  3104. if(selection.nStart > 0 && selection.nEnd > selection.nStart)
  3105. {
  3106. sample.SetLoop(selection.nStart, selection.nEnd, true, false, m_sndFile);
  3107. resetLoopOnCancel = true;
  3108. } else
  3109. {
  3110. Reporting::Error("Crossfade requires a sample loop to work.", this);
  3111. SwitchToView();
  3112. return;
  3113. }
  3114. }
  3115. if(sample.nLoopStart == 0 && sample.nSustainStart == 0)
  3116. {
  3117. Reporting::Error("Crossfade requires the sample to have data before the loop start.", this);
  3118. SwitchToView();
  3119. return;
  3120. }
  3121. CSampleXFadeDlg dlg(this, sample);
  3122. if(dlg.DoModal() == IDOK)
  3123. {
  3124. const SmpLength loopStart = dlg.m_useSustainLoop ? sample.nSustainStart: sample.nLoopStart;
  3125. const SmpLength loopEnd = dlg.m_useSustainLoop ? sample.nSustainEnd: sample.nLoopEnd;
  3126. const SmpLength maxSamples = std::min({ sample.nLength, loopStart, loopEnd / 2 });
  3127. SmpLength fadeSamples = dlg.PercentToSamples(dlg.m_fadeLength);
  3128. LimitMax(fadeSamples, maxSamples);
  3129. if(fadeSamples < 2) return;
  3130. PrepareUndo("Crossfade", sundo_update,
  3131. loopEnd - fadeSamples,
  3132. loopEnd + (dlg.m_afterloopFade ? std::min(sample.nLength - loopEnd, fadeSamples) : 0));
  3133. if(SampleEdit::XFadeSample(sample, fadeSamples, dlg.m_fadeLaw, dlg.m_afterloopFade, dlg.m_useSustainLoop, m_sndFile))
  3134. {
  3135. SetModified(SampleHint().Info().Data(), true, true);
  3136. } else
  3137. {
  3138. m_modDoc.GetSampleUndo().RemoveLastUndoStep(m_nSample);
  3139. }
  3140. } else if(resetLoopOnCancel)
  3141. {
  3142. sample.SetLoop(0, 0, false, false, m_sndFile);
  3143. }
  3144. SwitchToView();
  3145. }
  3146. void CCtrlSamples::OnStereoSeparation()
  3147. {
  3148. ModSample &sample = m_sndFile.GetSample(m_nSample);
  3149. if(!sample.HasSampleData()
  3150. || sample.GetNumChannels() != 2
  3151. || sample.uFlags[CHN_ADLIB])
  3152. {
  3153. MessageBeep(MB_ICONWARNING);
  3154. SwitchToView();
  3155. return;
  3156. }
  3157. static double separation = 100.0;
  3158. CInputDlg dlg(this, _T("Stereo separation amount\n0% = mono, 100% = no change, 200% = double separation\nNegative values swap channels"), -200.0, 200.0, separation);
  3159. if(dlg.DoModal() == IDOK)
  3160. {
  3161. separation = dlg.resultAsDouble;
  3162. SampleSelectionPoints selection = GetSelectionPoints();
  3163. PrepareUndo("Stereo Separation", sundo_update,
  3164. selection.nStart, selection.nEnd);
  3165. if(SampleEdit::StereoSepSample(sample, selection.nStart, selection.nEnd, separation, m_sndFile))
  3166. {
  3167. SetModified(SampleHint().Info().Data(), true, true);
  3168. } else
  3169. {
  3170. m_modDoc.GetSampleUndo().RemoveLastUndoStep(m_nSample);
  3171. }
  3172. }
  3173. SwitchToView();
  3174. }
  3175. void CCtrlSamples::OnAutotune()
  3176. {
  3177. SampleSelectionPoints selection = GetSelectionPoints();
  3178. if(!selection.selectionActive)
  3179. {
  3180. selection.nStart = selection.nEnd = 0;
  3181. }
  3182. ModSample &sample = m_sndFile.GetSample(m_nSample);
  3183. Autotune at(sample, m_sndFile.GetType(), selection.nStart, selection.nEnd);
  3184. if(at.CanApply())
  3185. {
  3186. CAutotuneDlg dlg(this);
  3187. if(dlg.DoModal() == IDOK)
  3188. {
  3189. BeginWaitCursor();
  3190. PrepareUndo("Automatic Sample Tuning");
  3191. bool modified = true;
  3192. if(IsOPLInstrument())
  3193. {
  3194. const uint32 newFreq = mpt::saturate_round<uint32>(dlg.GetPitchReference() * (8363.0 / 440.0) * std::pow(2.0, dlg.GetTargetNote() / 12.0));
  3195. modified = (newFreq != sample.nC5Speed);
  3196. sample.nC5Speed = newFreq;
  3197. } else
  3198. {
  3199. modified = at.Apply(static_cast<double>(dlg.GetPitchReference()), dlg.GetTargetNote());
  3200. }
  3201. OnFineTuneChangedDone();
  3202. if(modified)
  3203. SetModified(SampleHint().Info(), true, false);
  3204. EndWaitCursor();
  3205. }
  3206. }
  3207. SwitchToView();
  3208. }
  3209. void CCtrlSamples::OnKeepSampleOnDisk()
  3210. {
  3211. SAMPLEINDEX first = m_nSample, last = m_nSample;
  3212. if(CMainFrame::GetInputHandler()->ShiftPressed())
  3213. {
  3214. first = 1;
  3215. last = m_sndFile.GetNumSamples();
  3216. }
  3217. const bool enable = IsDlgButtonChecked(IDC_CHECK2) != BST_UNCHECKED;
  3218. for(SAMPLEINDEX i = first; i <= last; i++)
  3219. {
  3220. if(bool newState = enable && m_sndFile.SampleHasPath(i); newState != m_sndFile.GetSample(i).uFlags[SMP_KEEPONDISK])
  3221. {
  3222. m_sndFile.GetSample(i).uFlags.set(SMP_KEEPONDISK, newState);
  3223. m_modDoc.UpdateAllViews(nullptr, SampleHint(i).Info().Names(), this);
  3224. }
  3225. }
  3226. m_modDoc.SetModified();
  3227. }
  3228. // When changing auto vibrato properties, propagate them to other samples of the same instrument in XM edit mode.
  3229. void CCtrlSamples::PropagateAutoVibratoChanges()
  3230. {
  3231. if(!(m_sndFile.GetType() & MOD_TYPE_XM))
  3232. {
  3233. return;
  3234. }
  3235. for(INSTRUMENTINDEX i = 1; i <= m_sndFile.GetNumInstruments(); i++)
  3236. {
  3237. if(m_sndFile.IsSampleReferencedByInstrument(m_nSample, i))
  3238. {
  3239. const auto referencedSamples = m_sndFile.Instruments[i]->GetSamples();
  3240. // Propagate changes to all samples that belong to this instrument.
  3241. const ModSample &it = m_sndFile.GetSample(m_nSample);
  3242. m_sndFile.PropagateXMAutoVibrato(i, it.nVibType, it.nVibSweep, it.nVibDepth, it.nVibRate);
  3243. for(auto smp : referencedSamples)
  3244. {
  3245. m_modDoc.UpdateAllViews(nullptr, SampleHint(smp).Info(), this);
  3246. }
  3247. }
  3248. }
  3249. }
  3250. void CCtrlSamples::OnXButtonUp(UINT nFlags, UINT nButton, CPoint point)
  3251. {
  3252. if(nButton == XBUTTON1) OnPrevInstrument();
  3253. else if(nButton == XBUTTON2) OnNextInstrument();
  3254. CModControlDlg::OnXButtonUp(nFlags, nButton, point);
  3255. SwitchToView();
  3256. }
  3257. bool CCtrlSamples::IsOPLInstrument() const
  3258. {
  3259. return m_nSample >= 1 && m_nSample <= m_sndFile.GetNumSamples() && m_sndFile.GetSample(m_nSample).uFlags[CHN_ADLIB];
  3260. }
  3261. void CCtrlSamples::OnInitOPLInstrument()
  3262. {
  3263. if(m_sndFile.SupportsOPL())
  3264. {
  3265. CriticalSection cs;
  3266. PrepareUndo("Initialize OPL Instrument", sundo_replace);
  3267. m_sndFile.DestroySample(m_nSample);
  3268. m_sndFile.InitOPL();
  3269. ModSample &sample = m_sndFile.GetSample(m_nSample);
  3270. sample.nC5Speed = 8363;
  3271. // Initialize with instant attack, release and enabled sustain for carrier and instant attack for modulator
  3272. sample.SetAdlib(true, { 0x00, 0x20, 0x00, 0x00, 0xF0, 0xF0, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00 });
  3273. SetModified(SampleHint().Info().Data().Names(), true, true);
  3274. SwitchToView();
  3275. }
  3276. }
  3277. INSTRUMENTINDEX CCtrlSamples::GetParentInstrumentWithSameName() const
  3278. {
  3279. auto ins = m_modDoc.FindSampleParent(m_nSample);
  3280. if(ins == INSTRUMENTINDEX_INVALID)
  3281. return INSTRUMENTINDEX_INVALID;
  3282. auto instr = m_sndFile.Instruments[ins];
  3283. if(instr == nullptr)
  3284. return INSTRUMENTINDEX_INVALID;
  3285. if((!instr->name.empty() && instr->name != m_sndFile.m_szNames[m_nSample]) || instr->GetSamples().size() != 1)
  3286. return INSTRUMENTINDEX_INVALID;
  3287. return ins;
  3288. }
  3289. OPENMPT_NAMESPACE_END